One of the great benefits of Loo pseudo-OOP is that
local Person = {} function Person:create( firstName, lastName ) local person = { firstName=firstName, lastName=lastName } setmetatable(person,{__index=self}) return person end function Person:getFullName() return self.firstName .. " " .. self.lastName end local me = Person:create( "Gavin", "Kistner" ) local you = Person:create( "Eric", "Someone" ) print( me:getFullName() ) --> "Gavin Kistner" print( me.getFullName( you ) ) --> "Eric Someone"
I wrote an article discussing this (among other things):
Lua Training: Syntax and the Pseudo-OOP Domain .
Change The following example is shown here, for example jQuery each :
local Array = {} function Array:new(...) local a = {...} setmetatable(a,{__index=self}) return a end function Array:each(callback) for i=1,#self do callback(self[i],i,self[i]) end end function Array:map(callback) local result = Array:new() for i=1,#self do result[i] = callback(self[i],i,self[i]) end return result end function Array:join(str) return table.concat(self,str) end local people = Array:new( me, you ) people:each( function(self,i) print(self:getFullName()) end ) --> "Gavin Kistner" --> "Eric Someone" print( people:map(Person.getFullName):join(":") ) --> "Gavin Kistner:Eric Someone"
source share