您可能想要创建一个类声明函数来为您执行此操作。这是一个完整的“helper.lua”文件:
local lib = {type = 'helper'}
local CALL_TO_NEW = {__call = function(lib, ...) return lib.new(...) end}
function lib.class(class_name, tbl)
local lib = tbl or {}
lib.type = class_name
lib.__index = lib
-- Default "new" method
function lib.new()
return setmetatable({}, lib)
end
-- Enable foo.Bar() instead of foo.Bar.new()
return setmetatable(lib, CALL_TO_NEW)
end
return lib
使用示例:
local helper = require 'helper'
local lib = helper.class 'foo.Bar'
-- optional new function if there needs to be some argument handling
function lib.new(args)
local self = {}
-- ...
return setmetatable(self, lib)
end
return lib
润滑油类
这是一个真实世界的最小类声明和设置系统。它用于许多 luarocks,例如 xml、yaml、dub 等: