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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With