lua-users home
lua-l archive

Re: Syntax and redundancy

[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 = p.next
 end
Any nicer ways?
Write an iterator function.
do
 local function nextlist(field, l)
 return l and l[field]
 end
 function eachlist(l, field)
 field = field or "next"
 return nextlist, field, {[field] = l}
 end
end
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)
R

AltStyle によって変換されたページ (->オリジナル) /