Re: OOP help
Posted: Sat Feb 15, 2014 10:03 am
First of all, notice that this won't work:
tile.__index will receive 'nil', just because of one simple reason. The table with the field __index is created first. At that time, tile doesn't exist, so the field __index receives nil. Then the table is assigned to the variable "tile".
The right way to do it would be:
Second, about classes, keep in mind one thing. What you are calling a class should be like a "pattern". All instances from a class are supposed to know/use each and every single method defined in the class itself. For that matter, you do not need to define a draw method when you create an instance. Rather, move that draw instance in the class definition itself.
Also, it was not needed to have tile.create separated from tile.new, because they are supposed to do the same.
Updated code:
Hope this helps.
Code: Select all
tile = {__index = tile}
The right way to do it would be:
Code: Select all
tile = {}
tile.__index = tile
Also, it was not needed to have tile.create separated from tile.new, because they are supposed to do the same.
Updated code:
Code: Select all
-- The class itself
tile = {}
tile.__index = tile
-- Updates a tile
function tile:update(dt) end
-- Creates a new tile.
function tile.new(x,y,w,h)
local instance = {}
instance.x, instance.y = x, y
instance.w, instance.h = w or 32, h or 32
return setmetatable(instance, tile)
end
-- Draws a tile.
function tile:draw()
love.graphics.setColor(255,0,0,255)
love.graphics.rectangle("fill", self.x, self.y, self.w, self.h)
end