lua-users home
lua-l archive

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


Paul Sue <Paul.Sue <at> TELUS.com> writes:

> Is there another way I can traverse the table so I can preserve
> the order as I HTMLize it?

Your output is scrambled because pairs() traverses the table in an
unspecified order (which happens to be implemented as the opposite of 
what you want).  The following Project() does what you want, provided I
understand what you want.  (But see below.)

    function Project (table)
    
        -- Traverse string keys.  Values are parameters.
        for k,v in pairs(table) do
            if type(k) == "string" then print(k,v) end
        end
        
        -- Traverse number keys.  Values are subtables.
        for i,v in ipairs(table) do
            Project(v)
        end
    
    end
    
This traverses the parameters before the subtables, which I think you
want.  But the parameters will not be traversed in order, and I'm not
sure whether you're expecting that.  When you say something like:

    t = {
           server = "snoopy",
           IP = "142.27.9.31",
           {
               domain = "foo"
           },
           {
               domain = "bar"
           }
    }

it is equivalent to:

    t = {}
    t["server"] = "snoopy"
    t["IP"] = "142.27.9.31"
    t[1] = { domain = "foo" }
    t[2] = { domain = "bar" }

In particular, t["server"] and t["IP"] are not considered "before" or
"after" one other, and the order in which pairs() traverses them is
unspecified.  t[1] and t[2], on the other hand, have numerical indices,
so you can use ipairs() to traverse them in order.

-Bret