[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Why can't I do for...in on a table?
- From: Wim Couwenberg <wcou@...>
- Date: Mon, 12 Sep 2005 09:29:01 +0200
local t = { a = 1, b = "hello" }
for p in t do
print("t[",p,"] = ",t[p])
end
This works in 5.0 and I use it extensively.
This is legacy support in 5.0 and has been discussed at length. In 5.1
the support is dropped. The official construction is
for <vars> in <expression> do ... end
where expression is supposed to return three values:
function, data, key
nice to me, much nicer than table.foreach() or using pairs(). I know
that pairs has the nice feature that it gives me back the already
dereffed value.
The function pairs basically does just this:
function pairs(table) return next, table, nil end
so it uses next as its generator function. Lua 4 did that as well (but
in the same call frame).
Also, it seems like it would be more efficient to use a table directly
for a couple of reasons. First, the special code that must have been in
place to handle a table directly would be faster than having to make a
function call every time.
Lua 4 didn't reenter the VM at least. I suppose that was a bit faster.
Of course the VM of 5.0 is a fair bit faster overall.
> And if I just wanted the property and not the
value, pairs() will do a deref that I don't need.
That doesn't cost you anything extra, the value is stored in the same
table node as the key. Besides, Lua 4 did the same.
What problem was being caused by "for p in t do" ???
No problem really. I guess the new "generator" approach is found to be
generally more attractive (string.gmatch is an example). I know that
not everyone agrees.
--
Wim