Search code examples
for-looplualua-table

In pairs loop messed up


A normal working code but it doesn't work as i expected, seriously but wth Lua

local Exceptions = {1,2,3,5,7}
local mt = {__mod = function(v1, v2)
  for i, v in pairs (v1) do 
    if v2 == v then 
      return true
    else
      return false 
    end 
  end 
end }
setmetatable(Exceptions, mt)
print(Exceptions % 2)

v2 == v ( inside Exceptions has 2 so it should return true, but hell no, it returned false. This is annoying)


Solution

  • You break out of the pairs() loop when you return the result of v2 == v comparison. The value of 2 is never reached, you exit the __mod function prematurely, reporting the result of comparing 1 and 2.