2
votes

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
The second example prints john, after fixing the syntax in the definition of are to use ["stats"] = etc. - lhf
the data is the result of an unserialized plain-text array and why is using something like: - mpri
*The data is the result of an unserialized plain-text array. Why is using something like:print(tostring(arr['stats'][entry])) giving me a nil value? - mpri
As lhf points out, in your code, the syntax of arr is incorrect. Fix that and it would work just fine. If the data isn't exactly like what you put in the question, like you said in the comment, then show an example that people could reproduce your problem. - Yu Hao

1 Answers

1
votes

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...