In my main.lua, I spawn what should be two instances of said class, like so:
However, the slime instance is overwriting the position of the Player instance, and they both move together around the screen. It feels almost as if me calling the constructor method is behaving like a variable assignment, or something, except that somehow Player and slime are being linked together.
I've gone round and round on this for weeks, now, and I'm at my wits' end. I'm missing something simple, I know it. According to every Lua OOP tutorial I can find, this code SHOULD be working. And yet here I am.
If you replace "self = {}" with "self = self or {}", as in some Lua class tutorials, instead of both the Player and the slime, you just get the slime. I've tried rearranging the syntax, moving the functions of the class outside of the initial table of member variables, I've created a separate metatable that gets the setmetatable assignment. None of it makes a difference.
Here are the full source code of main.lua and Mob.lua, for reference:
Code: Select all
Map = require "./Classes/Map"
Mob = require "./Classes/Mob"
font = love.graphics.newFont("courier.ttf", 20)
love.graphics.setFont(font)
m1 = Map:New(20,10)
map1 = m1:makePlane(".")
Player = Mob:New(5,5,"@")
slime = Mob:New(1,1,"s")
global_timer = 0
function love.keyreleased(k)
if k == "escape" then
love.event.quit()
end
if k == "kp5" then -- wait
elseif k == "kp4" then -- move west
Player:Move(-1, 0)
elseif k == "kp6" then -- move east
Player:Move(1, 0)
elseif k == "kp8" then -- move north
Player:Move(0, -1)
elseif k == "kp2" then -- move south
Player:Move(0, 1)
elseif k == "kp1" then -- move SW
Player:Move(-1, 1)
elseif k == "kp7" then -- move NW
Player:Move(-1, -1)
elseif k == "kp9" then -- move NE
Player:Move(1, -1)
elseif k == "kp3" then -- move SE
Player:Move(1, 1)
end
end
function love.draw()
love.graphics.setColor(255,255,255)
for i = 1, m1.board_size.x do
for j = 1, m1.board_size.y do
if i ~= Player.position.x or j ~= Player.position.y then
love.graphics.print(map1[i][j], i * Map.tile_size, j * Map.tile_size)
end
end
end
love.graphics.setColor(255,0,0)
love.graphics.print(Player.character, Player.position.x * Map.tile_size, Player.position.y * Map.tile_size)
love.graphics.setColor(0,255,0)
love.graphics.print(slime.character, slime.position.x * Map.tile_size, slime.position.y * Map.tile_size)
end
Code: Select all
Mob = {
position = {
x = 0,
y = 0
},
character = " ",
New = function(self, x, y, char)
self = {}
setmetatable(self, Mob)
self.position.x = x
self.position.y = y
self.character = char
return self
end,
Move = function(self, dx, dy)
self.position.x = self.position.x + dx
self.position.y = self.position.y + dy
end
}
Mob.__index = Mob
return Mob