Rock48
Rock48

Reputation: 92

How do I index values in a multiple data type array in Lua?

This is a strange question but it baffles me. I want to be able to store x and y co-ords on an id based system such as: id.1.x = 10, id.1.y = 15: id.2.x = 50, id.2.y = 42 and I am trying to make a function to do it for me, I am having issues. here's my code

a = { p = {x,y}}
function box(xpos,ypos,id)
a[id].x = xpos
a[id].y = ypos
end
box(25,30,1)
box(45,10,2)
print(a[1].x.." "..a[1].y)
print(a[2].x.." "..a[2].y)

which I wanted to print:

25 30
45 10

but instead I get the error:

attempt to index global '?' (a nil value)

I am really exhausted and would like to put this to rest so if somebody could help it would be greatly appreciated.

Upvotes: 1

Views: 203

Answers (1)

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23747

function box(xpos,ypos,id)
  a[id] = {x = xpos, y = ypos}
end

Upvotes: 3

Related Questions