将函数作为变量传递并将其分配给仍然能够在 Lua 中引用 "self" 的对象

Passing a function as a variable and assigning it to an object still able to reference "self" in Lua

所以,我正在尝试编写一个函数,它接受函数作为其参数并将它们设置为 Lua 中的 'object' 方法。是否有我不知道的特定语法?

local function createObjectWithMethods(method1, method2)
    local object = {}
    object.meth1 = method1
    object:meth2 = method2 --this throws an error expecting parameters
    return object
end

还有其他方法吗?我知道我可以为对象硬编码一个方法,但是这段代码需要将函数作为参数传递,并且其中一些函数需要能够引用 self。有任何想法吗?

您需要在不使用自动 self 语法糖的情况下编写传入方法。

那是你不能用:

function obj:meth1(arg1, arg2)
    -- code that uses self
end

(除非这些函数在其他某个对象上定义并交叉应用于新对象)。

你自己写上面是什么糖

function meth1(self, arg1, arg2)
    -- code that uses self
end
function meth2(self, arg1, arg2)
    -- code that uses self
end

然后就可以正常调用函数,正常赋值了。

local function createObjectWithMethods(method1, method2)
    local object = {}
    object.meth1 = method1
    object.meth2 = method2
    return object
end

createObjectWithMethods(meth1, meth2)