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
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'
pgimeno wrote: ↑Sat Sep 21, 2024 4:34 am
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.
Last edited by DarkblooM on Sat Sep 21, 2024 8:18 am, edited 1 time in total.
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.
pgimeno wrote: ↑Sat Sep 21, 2024 4:34 am
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.
Ah OK, I'm still not fully used to "classes" in Lua haha. Thanks for the help.
You're welcome. Unrelated to classes, though, if you're using the return value of a function, that function needs to return something; otherwise you'll always get nil from it.
pgimeno wrote: ↑Sat Sep 21, 2024 9:22 am
You're welcome. Unrelated to classes, though, if you're using the return value of a function, that function needs to return something; otherwise you'll always get nil from it.
Yeah I know that, I just assumed that 'self' would be automatically returned, like in Python