arrayslualove2daddressing

Addressing an index in array in Lua


I am trying to write a simple game using Love 2d engine. It uses lua as the scripting language. I have some problems with arrays and can't find any solution. Here is my issue:

for i = 1, 10 do 
    objects.asteroids = {} 
    objects.asteroids[i] = {} 
    objects.asteroids[i].body = love.physics.newBody(world, 650/2, 650/2, "dynamic")
    objects.asteroids[i].size = 3 
    objects.asteroids[i].angle = math.random(6) 
end 

In the same function I am trying to do a following operation:

for i = 1, 10 do 
    objects.asteroids[i].size = 2 
end 

And I get this error when trying to run my game:

Error main.lua:48: attempt to index a nil value

Where line 48 refers to this line of code:

objects.asteroids[i].size = 2 

Solution

  • You're overwriting objects.asteroids on each loop iteration.

    for i = 1, 10 do
      objects.asteroids = {} -- <== Here.
      objects.asteroids[i] = {}
    

    What this means is that the asteroid objects that you're trying to add end up being erased on the next step of the loop, since object.asteroids is set to a new {} table and the old one becomes inaccessible thereafter.

    You might want to rearrange it like so:

    objects.asteroids = {}
    
    for i = 1, 10 do
      objects.asteroids[i] = {}
      -- ...