Log In  

Hi!

I hope this is the right place to ask...

So I gather I can make some enemies that have X-Y co-ordinates like this:

enemy = {
    x = 0,
    y = 0
}

enemies = {}

for i=1,5 do
    add(enemies, enemy)
    enemies[i].x = i * 5
    enemies[i].y = i * 10
    print(enemies[1].x)
end

(5 and 10 are arbitrary numbers for testing purposes.)

I believe this would be an array of tables.

I would have thought this would make 5 enemy co-ordinates, like this:

enemies[1].x = 5
enemies[1].y = 10

enemies[2].x = 10
enemies[2].y = 20

...and so on. But it looks like it's overwriting every enemy's co-ordinates with the latest pair each time.

Could someone please tell me what I'm doing wrong?

Cheers!

P#65432 2019-06-27 21:18

:: dredds

The code you’ve shown creates one enemy object. The loop adds 5 references pointing to that object into the table, and changes the coordinates of that one object five times.

Instead, create the objects inside the loop, so that each iteration creates a new object, and as a result you get five distinct objects in the array. Like this:

enemies = {}
for i = 1,5 do
  add(enemies, { x=1*5, y=i*10 })
end 
P#65434 2019-06-27 21:59
:: ZoeB

Ooooh, thank you so much!

P#65435 2019-06-27 22:20

[Please log in to post a comment]

Follow Lexaloffle:        
Generated 2020-07-15 23:48 | 0.010s | 4194k | Q:16