lua-users home
lua-l archive

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


Thanks. I find that regular ipairs does not work, but typing this in (from PiL 7.3) does:

    function iter (a, i)
      i = i + 1
      local v = a[i]
      if v then
        return i, v
      end
    end
    
    function ipairs (a)
      return iter, a, 0
    end
I was basically hoping to store children in a metatable. Right now I'm looking at doing it in the table directly to save this hassle. But am I to understand that Lua 5.2 allows me to specify the length operator in such a way that having children in the metatable would work?


On Tue, Dec 4, 2012 at 12:12 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
2012/12/4 Marc Lepage <mlepage@antimeta.com>:
> 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)
   i=i+1
   local v=rawget(getmetatable(a),i)
   if v then return i,v end
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?