gpt4 book ai didi

路亚: Dynamically calling a function with arguments

转载 作者:行者123 更新时间:2023-12-04 21:12:08 27 4
gpt4 key购买 nike

我尝试使用 Lua 动态调用带参数的函数。我想发送一个字符串以这样的方式进行解析:

  • 第一个参数是类实例“Handle”
  • 第二个是要调用的函数
  • 剩下的就是争论

“模块”是一个类似{ string=<instance of a class> } 的表格
split() 是一个简单的解析器,它返回一个带有索引字符串的表。

function Dynamic(msg)
local args = split(msg, " ")
module = args[1]
table.remove(args, 1)
if module then
module = modules[module]
command = args[1]
table.remove(args, 1)
if command then
if not args then
module[command]()
else
module[command](unpack(args)) -- Reference 1
end
else
-- Function doesnt exist
end
else
-- Module doesnt exist
end
end

当我通过“引用文献 1”尝试使用“ignore remove bob”时,它尝试在模块中与“ignore”关联的实例上调用“remove”,并给出包含在表中的参数“bob” (具有单个值)。

然而,在调用的另一端,remove 函数没有接收到参数。我什至尝试用

替换“引用 1”行
module[command]("bob")

但我得到了相同的结果。

这是另一个函数,它不接收参数 "bob" :

function TIF_Ignore:remove(name)
print(name) -- Reference 2
TIF_Ignore:rawremove(name)
TIF_Ignore:rawremovetmp(name)
print(title.. name.. " is not being ignored.")
end

当我试图找出问题所在时,我在我的代码中添加了“引用 2”。当我执行“ignore remove bob”时,或者当我将“Reference 1”中的“unpack(args)”替换为“bob”时,“remove”中的变量“name”仍然为 nil。

最佳答案

声明 function TIF_Ignore:remove(name) 等同于 function TIF_Ignore.remove(self, name)。注意在第一种情况下使用冒号,它添加了额外的隐藏参数来模拟 OOP 和类。调用该函数的方式是将“bob”作为 self 参数而不是 name 传递。

要解决此问题,您可以像这样制作remove“静态函数”:function TIF_Ignore.remove(name)。但是,您还必须以类似的方式更改 rawremoverawremovetmp,包括声明和调用站点。另一个(更简单的)选项是不从 args 表中删除 module,它应该是传递的第一个参数。

关于路亚: Dynamically calling a function with arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2441321/

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