Page 1 of 1

Error: attempt to index a nil value

Posted: Fri Sep 20, 2024 9:48 pm
by DarkblooM
Hello.

I'm taking my first steps into using LÖVE and I'm running into an issue that I can't quite identify.

Here's my main.lua:

Code: Select all

Player = {
  pos = {0, 0},
  speed = 0
}

function Player.new(pos, speed)
  local self = setmetatable({}, Player)
  self.pos = pos or {0, 0}
  self.speed = speed or 300
end

function love.load()
  player = Player.new({0, 0}, 300)
end

function love.update(dt)
  if love.keyboard.isDown("left")  then player.pos[1] = player.pos[1] - player.speed * dt end
  if love.keyboard.isDown("right") then player.pos[1] = player.pos[1] + player.speed * dt end
  if love.keyboard.isDown("down")  then player.pos[2] = player.pos[2] + player.speed * dt end
  if love.keyboard.isDown("up")    then player.pos[2] = player.pos[2] - player.speed * dt end
end

function love.draw()
  love.graphics.circle("fill", player.pos[1], player.pos[2], 10)
end
And here's the error message:

Code: Select all

Error: main.lua:24: attempt to index global 'player' (a nil value)
stack traceback:
	[string "boot.lua"]:777: in function '__index'
	main.lua:24: in function 'draw'
	[string "boot.lua"]:618: in function <[string "boot.lua"]:594>
	[C]: in function 'xpcall'
If needed, here's the packaged project: https://files.catbox.moe/k27voy.love

Re: Error: attempt to index a nil value

Posted: Sat Sep 21, 2024 4:34 am
by pgimeno
Hello, welcome to the forums. You're using the return value from Player.new() to set the variable `player`, yet you've forgetting to return a value within Player.new(). Simply add `return self` at the end of the function.