lua no class
It is a prototype based language。
在此語言中沒有class關鍵字來創建類。
現代ES6, 已經添加class類。 prototype based 語言沒啥優勢。
lua 如何構建class機制?
https://github.com/fanqingsong/oopclass.lua
提供lua的 Object Oriented Programing Class 實現: 比其他實現更加輕量 https://github.com/Yonaba/Lua-Class-System 特色功能: 1、 虛類聲明 2、 單例聲明 3、 類冰封, 一旦冰封后, 類的屬性不能被改變。
code -- oopclass.lua
local _M = {} -- Instantiates a class local function _instantiate(class, ...) -- 抽象類不能實例化 if rawget(class, "__abstract") then error("asbtract class cannot be instantiated.") end -- 單例模式,如果實例已經生成,則直接返回 if rawget(class, "__singleton") then -- _G[class]值為本class的實例 if _G[class] then return _G[class] end end local inst = setmetatable({__class=class}, {__index=class}) if inst.__init__ then inst:__init__(...) end --單例模式,如果實例未生成,則將實例記錄到類中 if rawget(class, "__singleton") then if not _G[class] then _G[class] = inst -- 對類對象增加實例獲取接口 class.getInstance = function ( self ) return _G[class] end -- 銷毀單例,為后續建立新單例准備 class.destroyInstance = function ( self ) _G[class] = nil end end end return inst end -- LUA類構造函數 function _M.class(base) local metatable = { __call = _instantiate, } -- 先查原型表,然后查父親類 metatable.__index=function(t, k) local v = t.__prototype[k] if v then return v end local parent = t.__parent if parent then return parent[k] end return nil end -- 緩存類的field metatable.__newindex=function (t,k,v) rawset(t.__prototype, k, v) end local _class = {} -- __parent 屬性緩存父類 _class.__parent = base or {} -- 存儲此類的所有field _class.__prototype = {} -- 在class對象中記錄 metatable ,以便重載 metatable.__index _class.__metatable = metatable -- 將類冷凍,不允許新建刪除修改 _class.freeze = function ( self ) local mt = getmetatable(self) mt.__newindex=function (t,k,v) error("class is frozen, cannot revise") end end return setmetatable(_class, metatable) end --- Test whether the given object is an instance of the given class. -- @param object Object instance -- @param class Class object to test against -- @return Boolean indicating whether the object is an instance -- @see class -- @see clone function _M.instanceof(object, class) local objClass = object.__class if not objClass then return false end while objClass do if objClass == class then return true end objClass = objClass.__parent end return false end return _M
使用
local oopclass = require("oopclass") local class = oopclass.class local instanceof = oopclass.instanceof local superTab = class() superTab.test = function ( self ) print("superTab test") end superTab:freeze() superTab.test2 = function ( self ) print("superTab test2") end local tab = class(superTab) local tabObj = tab() tabObj:test() print( instanceof(tabObj, tab) ) print( instanceof(tabObj, superTab) )