I'm starting learning Love2D (and Lua alongside), coming from an OOP background with C++ and C# I immediately tried gaining some insight in how to manage objects in lua. Using http://lua-users.org/wiki/ObjectOrientationTutorial, the first example "Simple metatable-based class" is what I used because it looked simple enough, and it works in native Lua. Of course it's not that simple when adapting it to Love2D...
Here is my current code:
Code: Select all
require("Hamster")
function love.load()
hamster = Hamster.new()
end
function love.update(dt)
hamster:update(dt)
end
function love.draw()
hamster:draw()
end
Code: Select all
Hamster = {}
Hamster.__index = Hamster
function Hamster.new()
local obj = {}
obj.img = love.graphics.newImage("hamster.png")
obj.x = 0
obj.y = 0
obj.speed = 300
-- setmetatable(obj, { __index = Hamster }) For some reason I need this or it will not work at all!
return obj
end
function Hamster:update(dt)
if love.keyboard.isDown("right") then
self.x = self.x + (self.speed * dt)
end
if love.keyboard.isDown("left") then
self.x = self.x - (self.speed * dt)
end
if love.keyboard.isDown("down") then
self.y = self.y + (self.speed * dt)
end
if love.keyboard.isDown("up") then
self.y = self.y - (self.speed * dt)
end
end
function Hamster:draw()
love.graphics.draw(self.img, self.x, self.y)
end