简单的面向对象

这是一个如何做一个非常简单的类系统的基本例子

Class = {}
local __instance = {__index=Class} -- Metatable for instances
function Class.new()
    local instance = {}
    setmetatable(instance, __instance)
    return instance
-- equivalent to: return setmetatable({}, __instance)
end

要添加变量和/或方法,只需将它们添加到类中即可。两个都可以为每个实例重写。

Class.x = 0
Class.y = 0
Class:getPosition()
    return {self.x, self.y}
end

并创建类的实例:

object = Class.new()

要么

setmetatable(Class, {__call = Class.new}
    -- Allow the class itself to be called like a function
object = Class()

并使用它:

object.x = 20
-- This adds the variable x to the object without changing the x of
-- the class or any other instance. Now that the object has an x, it
-- will override the x that is inherited from the class
print(object.x)
-- This prints 20 as one would expect.
print(object.y)
-- Object has no member y, therefore the metatable redirects to the
-- class table, which has y=0; therefore this prints 0
object:getPosition() -- returns {20, 0}