Domanda

I'm trying to make array of enemies and draw it, but i keep getting errors, if it is not about array itself its about bad argument in draw function: main.lua:38:bad argument#2 to 'rectangle'(number expected, got nil) Can anyone please explain what i'm doing wrong here is it use of generic for ?

Array code:

enemies = {}
for i=0,7 do
    enemies[i] = {}
    for j=0,2 do
        enemy = {}
        enemy.width = 40
        enemy.height = 20
        enemy.x = i * (enemy.width + 60) + 100
        enemy.y = enemy.height + 100
        table.insert(enemies[i],enemy)
    end

end
end

Draw function:

--enemy
love.graphics.setColor(0,255,255,255)
for i,v in ipairs(enemies) do
    love.graphics.rectangle("fill", v.x, v.y, v.width, v.height)
end
È stato utile?

Soluzione

enemies = {}
for i=1,8 do
    for j=1,3 do
        local enemy = {}
        enemy.width = 40
        enemy.height = 20
        enemy.x = i * (enemy.width + 60) + 100
        enemy.y = enemy.height + 100
        table.insert(enemies, enemy)
    end

end

I don't know, if that's what you intended though. Anyway, the reason why you got nil is that in your version ipairs return another table that contained three instances of enemy. For your version to work, you would have to add another ipairs:

for i,v in ipairs(enemies) do
    for _,e in ipairs(v) do
        love.graphics.rectangle("fill", e.x, e.y, e.width, e.height)
    end
end

Please remember to use local for function temporaries. And Lua arrays start at 1, not 0.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top