| Line 1: |
Line 1: |
| − | A complete tutorial about classes is written here: http://www.inspired-lua.org/2011/05/5-object-classes/ | + | A complete tutorial about classes is written here: http://inspired-lua.org/index.php/2011/05/5-object-classes/ |
| | | | |
| − | Here's how the class() function is defined, in the API : | + | Here's how the class([parent]) function is defined, in the API : |
| | | | |
| | <source lang="lua"> | | <source lang="lua"> |
| − | -- Class definition system
| |
| | class = function(prototype) | | class = function(prototype) |
| − | local derived = {}
| + | local derived={} |
| − | local derivedMT = {
| + | if prototype then |
| − | __index = prototype,
| + | function derived.__index(t,key) |
| − | __call = function(proto, ...)
| + | return rawget(derived,key) or prototype[key] |
| − | local instance = {}
| + | end |
| − | local instanceMT = {
| + | else |
| − | __index = derived,
| + | function derived.__index(t,key) |
| − | __call = function()
| + | return rawget(derived,key) |
| − | return nil, "attempt to invoke an instance of a class"
| + | end |
| − | end,
| + | end |
| − | }
| + | function derived.__call(proto,...) |
| − | setmetatable(instance, instanceMT)
| + | local instance={} |
| − | if instance.init then
| + | setmetatable(instance,proto) |
| − | instance:init(...)
| + | local init=instance.init |
| − | end
| + | if init then |
| − | return instance
| + | init(instance,...) |
| − | end,
| + | end |
| − | }
| + | return instance |
| − | setmetatable(derived, derivedMT)
| + | end |
| − | return derived
| + | setmetatable(derived,derived) |
| − | end | + | return derived |
| | + | end |
| | | | |
| | </source> | | </source> |