lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

2012/12/4 Marc Lepage <>:
> Hi, I have a table which has a metatable. I want to add children
> (other tables) to the metatable, not to the table directly.
> If I do so, I can get at them by t[1], t[2], t[3] and so on.
> But I can't do this:
> for i = 1, #t do
>     local child = t[i]
> end
> Because #t still returns 0.
> Comments and feedback welcome.
> I forgot to mention I'm using Lua 5.1.

Which does not have an __ipairs metamethod.

But you can still do this (adapted from PiL 7.3):

local function iter(a,i)
   local v=rawget(getmetatable(a),i)
   if v then return i,v end
local function ipairs(a) return iter,a,0 end
getmetatable(t).ipairs = ipairs

for k,v in t:ipairs() do print(k,v) end

BTW why do you use the metatable for this purpose instead of
a transparent proxy table as in PiL 13.4?