Paul
Paul

Reputation: 1327

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.

Upvotes: 4

Views: 12878

Answers (4)

xero
xero

Reputation: 4319

For future so readers, you can also use the module pattern. Create a file called counter.lua

local M = {}
M.coupledNumbers = {}

function M.insert(v)
    table.insert(M.coupledNumbers, v)
end
---@return table
function M.get()
    return M.coupledNumbers
end
---@return table
function M.staticList()
    return {
        ["name1"] = "value1",
        ["name2"] = "value2",
    }
end
return M

Then use it in your main logic:

local counter = require("counter")
local a = 10
for i = 1, 12 do
    for j = 1, 12 do
        counter.insert({ID = a, result = i*j})
        a = a + 10
    end
end
local pairs = counter.get()
for i = 1, #pairs do
    print(pairs[i].ID, pairs[i].result)
end

local list = counter.staticList()
print(list.name1)

Upvotes: 0

Allister
Allister

Reputation: 911

Dot notation and bracket notation are distinct. Your error is using both of them to index one thing. ([1].["ID"]) The problem is the .[

Dot notation: Table.a.b

Bracket notation: Table["a"]["b"]

If you want to mix them, you could do Table.a["b"] or Table["a"].b

So you want to do something like coupledNumbers[1].ID or coupledNumbers[1]["ID"]

It's really just personal preference as far as I know edit: See Pedro's answer for information on the use of variables in dot notation., although you can't get the nth item of an array with dot notation so you'll always index a number using[n]

Upvotes: 7

Piglet
Piglet

Reputation: 28950

From Lua 5.3 Reference Manual - 3.2 Variables

Square brackets are used to index a table:

var ::= prefixexp ‘[’ exp ‘]’

The syntax var.Name is just syntactic sugar for var["Name"]:

var ::= prefixexp ‘.’ Name

You may only use the dot notation to index a table value if your table key is a literal string. Having [ follow the dot operator doesn't make sense to the Lua interpreter as it expects a literal string.

Replace coupledNumbers[1].["ID"] with coupledNumbers[1].ID

Upvotes: 1

Pedro Alves
Pedro Alves

Reputation: 305

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.

Upvotes: 6

Related Questions