I'm learning lua and i'm trying the OOP approach. To start, I'm trying to make a grid class, but I think i'm still lacking some knowledge to make it do what I want it to do.
This is my code so far:
local screen = require( 'data.screen')
Grid = {}
Grid_mt = { __index = Grid }
--- Constructs a new Grid object.
function Grid:new( params )
local self = {}
local function try( self, event )
print(self.empty)
end
for i = 1, screen.tilesAcross do
if not self[i] then
self[i] = {};
end
for j = 1, screen.tilesDown do
self[i][j] = display.newImageRect( params.group, "images/playable.png", screen.tileWidth, screen.tileHeight )
self[i][j].x = (j - 1) * (screen.tileWidth + screen.tileSpacing) + screen.leftSpacing
self[i][j].y = (i - 1) * (screen.tileHeight + screen.tileSpacing) + screen.topSpacing
self[i][j]._x = i
self[i][j]._y = j
self[i][j].enable = false
self[i][j].empty = true
self[i][j].tap = try
self[i][j]:addEventListener( "tap", self[i][j] )
end
end
setmetatable( self, Grid_mt )
return self
end
function Grid:setEnable(value, x, y)
if value ~= true and value ~= false then
error("Boolean expected")
end
self[x][y].enable = value
end
function Grid:getEnable(x, y)
return self[x][y].enable
end
function Grid:setEmpty(value, x, y)
if value ~= true and value ~= false then
error("Boolean expected")
end
self[x][y].empty = value
end
function Grid:getEmpty(x, y)
return self[x][y].empty
end
function Grid:SetmColor()
self[1][4]:setFillColor( 255,255 )
end
I have 2 questions: My event works but I would like to do something like: print(self:getEmpty() ) but whenever I try to use a method in my event, it doesn't work "attempt to call method 'getEmpty' (a nil value)"
and also the setfillcolor wwon't work, I want to be able to change the color of a case with it.
Thanks for your time! and if i'm going to the wrong road, let me know, and by the way, I have a working code without make a class, this is just for training purpose :)
Thnaks!
The issue is that
self[i][j]
is not aGrid
, onlyself
is aGrid
. So when the event handler is called,self
in the handler is the display object, not theGrid
object. If the handler needs to know the grid object, you could assign the grid to each display object:then in
try
you could doBut in this case you may get a cleaner design if you have the tap handler not be specific to each display object. In this case you would use an upvalue, you can just use
self
:Since listener given is a function rather than a table, it gets only one parameter, the event, and self is an upvalue so it will be the Grid instance created just above the
try
function.For the first question, more information would be needed. See my comment above.
As for the
setFillColor
not working, the following is taken from the Corona docs:Now, when you are trying to execute:
you are passing the values for
gray
andalpha
channels. The values NEED TO BE less than, or equal to1
. Probably you want to pass1
(as 255 is generally the max. value)