lua-users home
lua-l archive

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

Christophe Jorssen <> wrote:
> Hello all,
> First of all, I'm quite new to lua so forgive me if
> - this is a silly question,
> - this is not the right place to ask such a silly question.
> I have the following code.
> --
> function traverse_table(t)
>   if t then
>      for k=1,#t do
>         if type(t[k] == "table") then
>            print("a table")
>            traverse_table(t[k])
>         else
>            print("not a table")
>         end
>      end
>   end
> end

There's a few things wrong with that function.  Here's the corrected
version (of what I think you intended):

function traverse_table(t)
  if t and type(t) == "table" then
     for k=1,#t do
        if type(t[k]) == "table" then
           print("a table")
           print("not a table")
     print("not a table")


You can take the length of a string using the '#' operator, but you
can't just index it like you can a table.  So the for loop didn't do
what you thought it would when 't' is a string.

Also, the parens around your type check were not correct.  You were
comparing if an element of the table was equal to the string "table"
and then taking the type of that.  Since that returns 'boolean', it is
always evaluated as true in the if statement.

James Graves