Reputation: 49
I am writing my first lua script with love2d and I am not sure why I am getting the error "main.lua:4 attempting to call global 'Player' a table value". My 2 scripts are below: --Main.lua
require("player")
function love.load()
p = Player()
end
function love.update(dt)
p:update(dt)
end
function love.draw()
p:draw()
end
--Player.lua
Player = {}
--variables for the player (size, position, speed)
function Player:new()
o = {
x = 30,
y = 30,
w = 20,
h = 20,
speed = 300,
}
setmetatable(player, { __index = Player })
end
function Player:update(dt)
if love.keyboard.isDown("a") then
player.x = player.x - player.speed * dt
end
if love.keyboard.isDown("d") then
player.x = player.x + player.speed * dt
end
if love.keyboard.isDown("w") then
player.y = player.y + player.speed * dt
end
if love.keyboard.isDown("s") then
player.y = player.y - player.speed * dt
end
end
function Player:draw()
love.graphics.rectangle("fill", o.x, o.y, o.w, os.h)
end
Upvotes: 0
Views: 1478
Reputation: 5857
You have a Player
table, implementing some class. That's a table, you shouldn't call it like p = Player()
. Call the new()
method instead:
function love.load()
p = Player:new()
end
Also, it seems there's bugs in that new()
too. You declare global o
variable (should be local really), and you return player
instead of o
, and there's no player
there at all. Fix it like this:
function Player:new()
local player = {
x = 30,
y = 30,
w = 20,
h = 20,
speed = 300,
}
return setmetatable(player, { __index = Player })
end
Upvotes: 1
Reputation: 542
Try to avoid global variables like Player in player.lua
, this is asking for trouble
This should work:
main.lua
local player = require("player")
function love.load()
p = player:new()
end
function love.update(dt)
p:update(dt)
end
function love.draw()
p:draw()
end
player.lua
local Player = {}
function Player:new()
local player = {
x = 30,
y = 30,
w = 20,
h = 20,
speed = 300,
}
self.__index = self
return setmetatable(player, self)
end
function Player:update(dt)
if love.keyboard.isDown("a") then
self.x = self.x - self.speed * dt
end
if love.keyboard.isDown("d") then
self.x = self.x + self.speed * dt
end
if love.keyboard.isDown("w") then
self.y = self.y + self.speed * dt
end
if love.keyboard.isDown("s") then
self.y = self.y - self.speed * dt
end
end
function Player:draw()
love.graphics.rectangle("fill", self.x, self.y, self.w, self.h)
end
return Player
Upvotes: 0