number expected, got nil
Posted: Wed Jun 07, 2023 6:51 pm
I've been trying to learn LÖVE for a few days now and I decided to code snake for a first project. Sadly, I get an error this error when trying to draw the head.
Error
main.lua:80: bad argument #2 to 'rectangle' (number expected, got nil)
Traceback
[love "callbacks.lua"]:228: in function 'handler'
[C]: in function 'rectangle'
main.lua:80: in function 'draw'
[love "callbacks.lua"]:168: in function <[love "callbacks.lua"]:144>
[C]: in function 'xpcall'
Here's the code, (the line the error occurred has a comment)
ASKING FOR ANY HELP
Error
main.lua:80: bad argument #2 to 'rectangle' (number expected, got nil)
Traceback
[love "callbacks.lua"]:228: in function 'handler'
[C]: in function 'rectangle'
main.lua:80: in function 'draw'
[love "callbacks.lua"]:168: in function <[love "callbacks.lua"]:144>
[C]: in function 'xpcall'
Here's the code, (the line the error occurred has a comment)
Code: Select all
function love.load()
love.window.setMode(700, 700)
update = 0
snake = {
length = 1,
speed = 4,
facing = 0,
bodyX = {0},
bodyY = {0}
}
food = {
x = love.math.random(1, 20) * 35,
y = love.math.random(1, 20) * 35
}
end
function love.update(dt)
if love.keyboard.isDown("w", "up") then
snake.facing = 1
elseif love.keyboard.isDown("a", "left") then
snake.facing = 2
elseif love.keyboard.isDown("s", "down") then
snake.facing = 3
elseif love.keyboard.isDown("d", "right") then
snake.facing = 4
end
if update == 0 then
if snake.facing == 1 then
snake.bodyY[1] = snake.bodyY[1] - 35
elseif snake.facing == 2 then
snake.bodyX[1] = snake.bodyX[1] - 35
elseif snake.facing == 3 then
snake.bodyY[1] = snake.bodyY[1] + 35
elseif snake.facing == 4 then
snake.bodyX[1] = snake.bodyX[1] + 35
end
end
if snake.bodyX[1] == food.x then
if snake.bodyY[1] == food.y then
food.x = love.math.random(1, 19) * 35
food.y = love.math.random(1, 19) * 35
snake.length = snake.length + 1
snake.bodyX[snake.length] = snake.bodyX[snake.length - 1]
snake.bodyY[snake.length] = snake.bodyY[snake.length - 1]
end
end
for i = 1, snake.length, 1 do
snake.bodyX[i] = snake.bodyX[i - 1]
snake.bodyY[i] = snake.bodyY[i - 1]
end
if update == snake.speed then
update = 0
else
update = update + 1
end
end
function love.draw()
love.graphics.setBackgroundColor(0.5, 0.9, 0.6)
love.graphics.setColor(1, 1, 1)
for i = 700, 1, -35 do
love.graphics.line(i, 0, i, 700)
love.graphics.line(i + 1, 0, i + 1, 700)
love.graphics.line(0, i, 700, i)
love.graphics.line(0, i + 1, 700, i + 1)
end
love.graphics.setColor(0, 0, 0)
love.graphics.rectangle("fill", snake.bodyX[1], snake.bodyY[1], 35, 35) --This is were the error is
love.graphics.setColor(1, 0.5, 0.5)
love.graphics.rectangle("fill", food.x, food.y, 35, 35)
end