Lua multidimensional table call

1.6k views Asked by At

I seem to be having a problem with multidimensional tables (arrays?) on Lua. I have one that looks something like this:

arr =
{
  "stats" = {
         "23" = {
                "1" = { 
                  "account_id" = "10",
                  "info" = {
                            "name" = "john"
                           }
                      }
                 }
             }
}

and whenever I try to access some info using like:

local entry = "23"
print(arr['stats'][entry]['1'])

or

print(arr['stats'][entry]['1']['info']['name'])

I get nil values, is mixing strings with variables when calling tables even allowed? any idea what I'm doing wrong?

1

There are 1 answers

3
Luiz Menezes On BEST ANSWER

It seems that lua does not accepts things like

arr = { "string" = "value"}

so, either you do

arr = { string = "value"}

or you do

arr = {["string"] = value}

That way, your table must be rewritten as this, in order to run on lua 5.3 interpreter:

arr =
{
   stats =
   {
      ["23"] = 
      {
        ["1"] =
        {
          account_id = "10",
          info = 
          {
            name = "john"
          }
        }
      }
   }
}

doing this, your line

print(arr['stats'][entry]['1']['info']['name'])

runs fine.

Also, it is not good practice to use brackets when you can use a dot. It is not that your script will not run otherwise, but the code gets a lot more legible and easier to debug if you wirte that line like this:

print(arr.stats[entry]['1'].info.name)

Hope that helps...