Difference between revisions of "class"

From Inspired-Lua Wiki
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 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>

Revision as of 00:58, 15 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