Search code examples
for-loopluaindexingnulllove2d

Lua 2D array error


So I am fairly new to Lua, and in other languages I have been able to create a 2D array of variables and simply index through the array in order to create a tiled map. Whenever I try this in lua I get an error (specifically an error stating that I am indexing a nil value). How can I fix this?

CODE

function love.load()
love.graphics.setColor(255,255,0)
tile = love.graphics.newImage("lightGrass.png")
map = { {1,1,0,0,0,0,0,0,0,0},
        {0,1,0,0,0,0,0,0,0,0},
        {0,1,0,0,0,0,0,0,0,0},
        {1,1,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0}
    }
end

function love.draw()
    for i = 0, 10 do
        for j = 0, 10 do
            newPos = map[i][j]
            if newPos == 0 then -- this is where the error is!!!!!!!!!!!!!!!
                love.graphics.draw(tile,j * 32, i * 32)
            end
        end
    end

end

function love.update(dt)

end

Solution

  • Arrays in Lua start at 1, not at 0. So your for loops must begin at 1.