2

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?

4
  • 3
    The second example prints john, after fixing the syntax in the definition of are to use ["stats"] = etc. Commented Dec 25, 2016 at 22:18
  • the data is the result of an unserialized plain-text array and why is using something like: Commented Dec 25, 2016 at 22:24
  • *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? Commented Dec 25, 2016 at 22:25
  • 4
    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. Commented Dec 26, 2016 at 3:35

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

did Lua ever allow to have a string as a field name without brackets?
I remember doing that in Lua 5.1, but I may be mistaken.
You are mistaken, Lua never allowed string literal as a key without bracketing it first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.