Page 1 of 1

Add __ipairs metatable event on LuaCustomTable

Posted: Fri Jul 29, 2016 2:47 am
by aubergine18
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:

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

Re: Add __ipairs metatable event on LuaCustomTable

Posted: Fri Jul 29, 2016 11:03 am
by Rseding91
Why? Just don't ever use ipairs.

As I said on reddit when someone else was having issues like this: ipairs is just a shitty version of pairs that works less often.

Re: Add __ipairs metatable event on LuaCustomTable

Posted: Fri Jul 29, 2016 11:39 am
by aubergine18
I was always under the impression that ipairs was faster than pairs, "because numerical referencing"?

Re: Add __ipairs metatable event on LuaCustomTable

Posted: Sat Jul 30, 2016 12:56 am
by Rseding91
The code would be identical on the Factorio side if the name was ipairs or pairs.

As for the speed, I've never measured it but if you're iterating over a table that only has indexed items it's going to be the same speed as pairs anyway since the internals work the same way.