我知道这个网站上有一些关于在 Lua 中实现 OOP 的问题,但是,这个问题有点不同(至少与我发现的相比)。
我正在尝试创建一个名为“ human ”的类,并使其使用“ human”的“新”构造函数创建的对象继承 human 内部除构造函数之外的所有内容。然而,我也不希望能够在人类内部、人类身上使用方法。因此,人类类中的任何内容都只会传递给创建的对象。这是一个例子:
-- "Human" class
human = {}
function human.new(name)
local new = {} -- New object
-- Metatable associated with the new object
local newMeta =
{
__index = function(t, k)
local v = human[k] -- Get the value from human
print("Key: ", k)
if type(v) == "function" then -- Takes care of methods
return function(_, ...)
return v(new, ...)
end
else
return v -- Otherwise return the value as …Run Code Online (Sandbox Code Playgroud)