在Lua中,将一个函数作为变量传递并赋值给一个对象,仍然可以引用"self"。

因此,我正在尝试编写一个函数,它接受函数作为其参数并将它们设置为 Lua 中的“对象”方法。我不知道是否有特定的语法可以做到这一点?

local function createObjectWithMethods(method1, method2)
    local object = {}
    object.meth1 = method1
    object:meth2 = method2 --这会引发需要参数的错误
    return object
end

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

点赞
用户258523
用户258523

你需要写传入的方法而没有自动的 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)
2015-04-08 16:07:42