lua-users home
lua-l archive

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


    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