netsocket
netsocket

Reputation: 137

Understanding how to access objects in lua

The closest i've gotten to figuring this out, came from this post Understanding how to access values in array of tables in lua which actually has the most useful information i've seen. However, I'm still running into a minor issue that I hope someone could help me make more sense of it.

As the title states, I'm trying to access an object in lua. I've learned that dot notation doesn't work, so the alternative is to use [] brackets. I have this object here that I can't seem to access.

                    [1] =  ▼  {
                       ["CopperOre"] =  ▼  {
                          ["Counter"] = 0,
                          ["Earned"] = 0
                       }
                    } 

This was a paste from the ROBLOX studio console, for those who are familiar with it. This object can easily be seen by calling the object name print(obj)

However, I can't seem to access anything inside of the object. obj.CopperOre returns nil, same with obj['CopperOre']

How exactly do I access the parts of the object?

Upvotes: 2

Views: 865

Answers (1)

Kylaaa
Kylaaa

Reputation: 7188

You are forgetting to pass the index into the obj array to access the object stored there.

So to properly access the CopperOre table, you need to reference it like this :

print(obj[1].CopperOre)
-- or
print(obj[1]["CopperOre"])

Upvotes: 3

Related Questions