Add __ipairs metatable event on LuaCustomTable
Posted: Fri Jul 29, 2016 2:47 am
In Lua 5.2, the __pairs and __ipairs metamethods were added, allowing override of the default pairs/ipairs iterators.
If ipairs(someTable) is called, the ipairs() function first checks someTable's metatable to see if it has an __ipairs event, and, if found, it uses that as the iterator instead.
The custom __ipairs event (function) could check to see if `#` is defined for the custom table (ie. is it an array?), and, if not, revert to the custom __pairs event instead.
IMO this would make working with custom tables much easier, as modders won't have to worry about using pairs/ipairs on such tables, it will "just work", regardless of whether the table is numerically-indexed or not.
Some additional infos can be found here: http://lua-users.org/wiki/GeneralizedPairsAndIpairs
For reference, here's ipairs() implemented in plain lua:
If ipairs(someTable) is called, the ipairs() function first checks someTable's metatable to see if it has an __ipairs event, and, if found, it uses that as the iterator instead.
The custom __ipairs event (function) could check to see if `#` is defined for the custom table (ie. is it an array?), and, if not, revert to the custom __pairs event instead.
IMO this would make working with custom tables much easier, as modders won't have to worry about using pairs/ipairs on such tables, it will "just work", regardless of whether the table is numerically-indexed or not.
Some additional infos can be found here: http://lua-users.org/wiki/GeneralizedPairsAndIpairs
For reference, here's ipairs() implemented in plain lua:
Code: Select all
function ipairs(t)
local function ipairs_it(t, i)
i = i+1
local v = t[i]
if v ~= nil then
return i,v
else
return nil
end
end
return ipairs_it, t, 0
end