arraysluanestedkey

Understanding how to access values in array of tables in lua


teaching myself lua and trying to work out how to access keys and values in nested tables when you have an array of them. If I had for example the following table:

local coupledNumbers = {}
local a = 10
for i = 1, 12 do
    for j = 1, 12 do
        table.insert(coupledNumbers, {ID = a, result = i*j})
        a = a + 10
    end
end

This loop will give me the keys (1 to 144)

for k, v in pairs (coupledNumbers) do
    print (k)
end

This loop will give me the values (something along the lines of: table: 0xc475fce7d82c60ea)

for k, v in pairs (coupledNumbers) do
    print (v)
end

My question is how do I get into the values inside the table?

how do I get ID and result. I thought something like that would work:

print (coupledNumbers[1].["ID"])

or

print (coupledNumbers[1].["result"])

But it gives an error.


Solution

  • As Allister correctly put, the error is precisely in putting .[. But I want to add something: dot notation and bracket notation can do the same, but that is not always the case.

    What I would like to add is that bracket notation allows you to use variables to reference fields. For example, if you have the following piece:

    local function getComponent(color, component)
       return color[component]
    end
    
    local c = {
       cyan = 0,
       magenta = 11,
       yellow = 99,
       black = 0
    }
    
    print(getComponent(c, "yellow"))
    

    You simply can't do this using dot notation. The following would always return nil:

    local function getComponent(color, component)
       return color.component
    end
    

    That's because it would search for a field called component in color (which wouldn't exist, in this model).

    So, basically, what I want to highlight is that, if you know the field, dot notation is fine, but, if it may vary, use brackets.