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

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. :) (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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
views:1654 update:2011/10/5 8:48:05
corona forums © 2003-2011