OliveOil
OliveOil

Reputation: 13

How do I get a value by index from a nested table in lua?

I've been making a game with the LOVE2D game engine, and I've stumbled across an issue. I want to access a variable inside a nested table, but I don't know how.

Here's my code right now:

local roomNum = 1
local rooms = { r1 = { complete = false, name = "Room 1" }

if rooms[roomNum].complete == true then --problematic line
    --do stuff
end

If I replace rooms[roomNum].complete with rooms.r1.complete then it works.

Any help would be appreciated!

Upvotes: 1

Views: 624

Answers (1)

eparham7861
eparham7861

Reputation: 205

'http://lua-users.org/wiki/TablesTutorial'

The provided link gives easy to understand examples on tables in Lua, so it may prove a useful resource in the future.

As for the why the replacement code worked, a dictionary is just sets of key/value pairs (kvp) . In examples from other languages, these pairs are normally shown as something like KeyValuePair.

In your case, you are using a variation on how dictionaries are used. As you have seen, you can use numbered indexes like room[1], or you can use a string like room["kitchen"]. It gets interesting when you provide a set of data to initialize the dictionary.

Building off of the provided data, you have the following:

local rooms = { r1 = { complete = false, name = "Room 1" } 

r1 is equivalent to using rooms["r1"] without the dataset. In providing the dataset, any "named" Key can be referenced like it is a property of the dictionary (think of classes with public getter/setter). For the named keys of a dataset, you can provide a key as numbers as well.

local rooms = { [1] = { complete = false, name = "Room 1" }

This indexing fits the direction you were headed on providing a room index. So, you could either swap the dataset to use integers instead of r1, r2 and so on, or you could concatenate r and the index numbering. That is pretty much up to you. Keep in mind as you go further down nesting the same rules apply. So, complete could look like rooms[1].complete, rooms["r1" ].complete, or rooms.r1.complete.

Upvotes: 1

Related Questions