문제

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
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top