Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve X, Y coords from nested Lua table

Tags:

lua

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

like image 227
George Phillipson Avatar asked Feb 08 '23 17:02

George Phillipson


2 Answers

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.

like image 131
Paul Kulchenko Avatar answered Feb 17 '23 02:02

Paul Kulchenko


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
like image 28
warspyking Avatar answered Feb 17 '23 00:02

warspyking