lua-users home
lua-l archive

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

On 30-Aug-05, at 11:22 AM, Chris Marrin wrote:

I would do it like this:

    local l = { }
    ... fill the list
    local p = l
    while p ~= nil do
        p =

Any nicer ways?

Write an iterator function.

  local function nextlist(field, l)
    return l and l[field]

  function eachlist(l, field)
    field = field or "next"
    return nextlist, field, {[field] = l}

list = {"a", next = {"b", next = {"c"}}}
for l in eachlist(list) do print(l[1]) end

-- maybe I didn't want to use "next"
list = {"a", parent = {"b", parent = {"c"}}}
for l in eachlist(list, "parent") do print(l[1]) end

Whether that's nicer or not depends on your perspective, I guess. The redundant table constructor is a bit irritating, and in any event it's going to be somewhat slower than the while loop. On the other hand, it's a nice simple syntax which makes it easy to see what's going on.

(Open to being criticised for doing the Lua equivalent of Boyko's DO macro)