Difference between revisions of "class"
Jump to navigation
Jump to search
(Created page with "A complete tutorial about classes is written here: http://www.inspired-lua.org/2011/05/5-object-classes/ Here's how the class() function is defined, in the API : <source lang="...") |
|||
Line 4: | Line 4: | ||
<source lang="lua"> | <source lang="lua"> | ||
− | |||
class = function(prototype) | class = function(prototype) | ||
− | + | local derived={} | |
− | + | if prototype then | |
− | + | function derived.__index(t,key) | |
− | + | return rawget(derived,key) or prototype[key] | |
− | + | end | |
− | + | else | |
− | + | function derived.__index(t,key) | |
− | + | return rawget(derived,key) | |
− | + | end | |
− | + | end | |
− | + | function derived.__call(proto,...) | |
− | + | local instance={} | |
− | + | setmetatable(instance,proto) | |
− | + | local init=instance.init | |
− | + | if init then | |
− | + | init(instance,...) | |
− | + | end | |
− | + | return instance | |
− | + | end | |
− | + | setmetatable(derived,derived) | |
− | end | + | return derived |
+ | end | ||
</source> | </source> |
Revision as of 23:58, 14 March 2012
A complete tutorial about classes is written here: http://www.inspired-lua.org/2011/05/5-object-classes/
Here's how the class() function is defined, in the API :
class = function(prototype)
local derived={}
if prototype then
function derived.__index(t,key)
return rawget(derived,key) or prototype[key]
end
else
function derived.__index(t,key)
return rawget(derived,key)
end
end
function derived.__call(proto,...)
local instance={}
setmetatable(instance,proto)
local init=instance.init
if init then
init(instance,...)
end
return instance
end
setmetatable(derived,derived)
return derived
end