简体   繁体   English

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

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

So, I'm trying to write a function which accepts functions as its parameters and sets them as 'object' methods in Lua. 所以,我正在尝试编写一个接受函数作为参数的函数,并将它们设置为Lua中的“对象”方法。 Is there a specific syntax for this of which I'm not aware? 是否有一个我不知道的特定语法?

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

Is there another way to go about this? 还有另一种方法可以解决这个问题吗? I know that I could hardcode a method for the object, but this code needs to have functions passed as parameters, and some of those functions need to be able to reference self. 我知道我可以硬编码对象的方法,但是这段代码需要将函数作为参数传递,其中一些函数需要能够引用self。 Any ideas? 有任何想法吗?

You need to write the passed-in methods without the automagic self syntax sugar. 你需要编写传入的方法而不需要自动化的self语法糖。

That is you can't use: 那就是你不能用:

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

(unless these functions are defined on some other object and being cross-applied to the new object). (除非这些函数在某个其他对象上定义并交叉应用于新对象)。

Instead you need to write what the above is sugar for yourself. 相反,你需要为自己写出上面的糖。

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

Then you can just call the function normally and assign the functions normally. 然后你可以正常调用函数并正常分配函数。

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