Object oriented Lua

First off, I’m new to Lua. I’ve created a couple of classes in my current game project using something similar to the method described here, and it seems to work fine.

http://lua-users.org/wiki/SimpleLuaClasses

But there are several ways to do this. Is there a recommended best practice?

http://lua-users.org/wiki/ObjectOrientedProgramming [import]uid: 58455 topic_id: 12416 reply_id: 312416[/import]

there isn’t really a recommended best practice for OO in Lua because nothing is defined by the language itself. because of the loose nature of the language, this means that there is more than one way to “skin the cat” of OO development depending on what your definition of OO happens to be at the time. :slight_smile: (eg, Mix-ins, duck typing, etc)

i published a Corona library which implements the more classical variety of OO and includes some of the ideas taken from the PIL and the lua-users wiki, those links which you posted.

http://developer.anscamobile.com/code/dmc-corona-library

there’s documentation and several examples.

cheers,
dmc [import]uid: 74908 topic_id: 12416 reply_id: 56112[/import]

We expanded on the SimpleLuaClasses class() concept and wrote a derivation so that our code is architected like the example below.

require "class"  
  
Hero = class( display.newGroup )  
  
function Hero:constructor( name, sprite )  
  
 self.name = name  
 self:insert( sprite )  
end  
  
function Hero:attack( target )  
  
 target:attackedBy( self )  
end  
  
function Hero:dispose()  
  
 print( 'goodbye cruel world' )  
 self:removeSelf()  
end  
  
Mage = class( Hero )  
  
function Mage:attack( target )  
  
 self.\_super.attack( self, target )  
 self:depleteMana()  
end  
  
function Mage:depleteMana()  
  
 --deplete mana, of course. Get Caramon will you?  
end  
  
local enemy = Ogre()  
local player = Mage( 'Raistlin', display.newImage( 'mage.png' ))  
print( player.name ) -- Raistlin  
player:attack( enemy )  
player:dispose() -- goodbye cruel world  
player = nil  

It allows for extension of the Corona display classes, and doesn’t have that ugly mishmash of class & constructor declaration: class(function(self, param) end). So far it’s worked great. [import]uid: 4596 topic_id: 12416 reply_id: 56118[/import]