carlos…
i came up with something similar without metatable or __index. it works, so please could you help me understand why i might need those? (in my other class implementation i did use those, but they work without them here. maybe it’s why i need to use “this” in my code?)
I’ve seen about 3 ways of doing “classes” but this one below seems quite good to me.
(I’m new to all this though, so i don’t know if i’ve got elements in there which are not optimal for speed)
file: BallActor.lua
[lua]module(…, package.seeall)
TableUtils = require(“TableUtils”)
function new(x,y,img) – Constructor
local this = {}
– private vars, but synthesized with getter/setter on this,
– to make them public on object
local group
local contacts
local sprite
– private, not synthesized below
local groupRedefined
– create the graphic for the actor
sprite = display.newImage(img);
sprite.x = 60 + math.random( 160 )
sprite.y = -100
sprite.type= string.gsub(img, “.png”,"")
sprite.is = “BallActor”
– initalize collision info
group = {this}
contacts = {}
– synthesize public variables (getter/setter)
this.sprite = sprite
this.actor = this
this.sprite.actor = this
this.group = group
this.contacts = contacts
–
function this:say()
print("I am a BallActor with sprite id = "…sprite.id)
end
–
function this:resetGroup()
group = {this}
groupRedefined = false
end[/lua]
main.lua:
[lua]function newBall()
local rand = math.random( 100 )
local x = 60 + math.random(160)
local y = -100
local ball
if(spriteCount < MAX_BALLS) then
– create instance of BallActor “class” (this isn’t a display object, but includes a sprite reference)
ball = BallActor.new(x,y,“ball.png”)
spriteCount = spriteCount+1
ballIDCount = ballIDCount+1
– sprite variable is “synthesised” in our BallActor class (ObjC terminology)
– basically means it is public variable on the class instance
ball.sprite.id = ballIDCount
– call a public class method
ball.say()
print(“sprite=”…tostring(ball.sprite))
print(“sprite.id=”…ball.sprite.id)
world:insert(ball.sprite)
_.push(balls,ball)
physics.addBody(ball.sprite)
end
end
local dropBall = timer.performWithDelay( 50, newBall,-1)[/lua]
thanks for any feedback
J [import]uid: 6645 topic_id: 3515 reply_id: 10606[/import]