I need to get the values from a nested table in Lua, I just cannot figure out how to do it, I have tried numerous online examples but none work.
Any help would be appreciated
table
xy = { a={x=0,y=0},b={x=0,y=100}, c={x=0,y=200}}
if unpack(route) contains a and c, how can I get the x,y values from the table above.
I have tried
for _, v in pairs(xy) do
print(v[1], v[2])
end
But all i get back is nil
Since pairs
give you key, value
pair, the value
part is the table with x
and y
values; now you can simply do:
print(v.x, v.y)
Using v[1]
and v[2]
retrieves first and second element of that table, but these are not x
and y
elements, so that's why you get nil
in your case.
In general, nested tables are accessed in the same way: t.index1.index2
, etc. If indexes are numeric, then you need to use t[1][2]
notation, which means: get the second element of the table retrieved as the first element of table t
.
You are not using arrays, therefore neither unpack nor numerical indexing is going to help you. Instead you can use syntactic sugar:
print(xy.a.x, xy.a.y)
If you wish to loop over them all:
for i,v in pairs(xy) do
print(i..": "v.x, v.y)
end
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