gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:33:06 25 4
gpt4 key购买 nike

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

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

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

最佳答案

您需要编写没有 automagic 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)

关于mobile - 将函数作为变量传递并将其分配给仍然能够在 Lua 中引用 "self"的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29519676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com