簡單的物件導向

這是一個如何做一個非常簡單的類系統的基本例子

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}