From: Gavin Kistner Date: 2005-10-19T22:06:57+09:00 Subject: Re: Factory function like Array() for your own classes On Oct 14, 2005, at 8:00 PM, Sean O'Halpin wrote: > This makes it possible to define factory functions that work like the > built-in Array() and String() functions, e.g. so that Thing(1,2,3) is > the same as Thing.new(1,2,3). A language-comparison-aside... In Lua, every table (the core object unit; basically a Hash with some extra goodies) can be accessed directly OR called as a function, if the table's metatable has a __call property that points to a function. For example: Person = { -- constructor new=function( self, inName, inAge ) local theInstance = { name = inName or "John", age = inAge or 0 } -- make the instance inherit from the 'class' setmetatable( theInstance, self._instanceMetaTable ) return theInstance end, -- methods and properties common to all instances prototype = { species = 'Human', greet = function( self ) print( "Hello, my name is " .. self.name ) end } } Person._instanceMetaTable = { __index = Person.prototype, __tostring = function( self ) return string.format( '', self.name, self.age ) end } -- Here's the magic that makes the Person table callable as a function setmetatable( Person, { __call = function( self, ... ) return self:new( unpack( arg ) ) end } ) local gk = Person:new( 'Gavin', 32 ) local lk = Person( 'Lisa', 31 ) print( gk, lk ) --> Person.prototype.greet( gk ) --> Hello, my name is Gavin gk:greet( ) --> Hello, my name is Gavin lk:greet( ) --> Hello, my name is Lisa -- Showing that Person isn't a function, just an object with properties print( Person.prototype ) --> table: 0x303a40