繁体   English   中英

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

[英]Passing a function as a variable and assigning it to an object still able to reference “self” in Lua

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM