lua-users home
lua-l archive

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


Adrian Perez wrote:

...
How is that done in Lua? This is both trying to illustrate that C's for loop has nice flexibility, and trying to understand how you would do something like this in Lua! 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?


I propose the following:

local l = { }
... fill the list
for _,value in l do
   ...
end

Of course, you may also write:

local l = { }
... fill the list
table.foreachi(l, function(_,value) ... end)

But that's not the same. That just iterates over the properties of a single table. I want a linked list of tables, where each table contains a 'next' property which refers to the next table in the list. The last table would have a next value of nil. You could argue that you SHOULD do it as a single table of properties, but that doesn't illustrate the example :-)

--
chris marrin                ,""$,
chris@marrin.com          b`    $                             ,,.
                        mP     b'                            , 1$'
        ,.`           ,b`    ,`                              :$$'
     ,|`             mP    ,`                                       ,mm
   ,b"              b"   ,`            ,mm      m$$    ,m         ,`P$$
  m$`             ,b`  .` ,mm        ,'|$P   ,|"1$`  ,b$P       ,`  :$1
 b$`             ,$: :,`` |$$      ,`   $$` ,|` ,$$,,`"$$     .`    :$|
b$|            _m$`,:`    :$1   ,`     ,$Pm|`    `    :$$,..;"'     |$:
P$b,      _;b$$b$1"       |$$ ,`      ,$$"             ``'          $$
 ```"```'"    `"`         `""`        ""`                          ,P`
"As a general rule,don't solve puzzles that open portals to Hell"'