简体   繁体   English

LUA - 如何使用_G [x]()方法从字符串中调用函数

[英]LUA - How to call a function from a string using the _G[x]() method

I'm having a problem with my code and I don't know what's up, I've searched online and the _Gx method was suggested as the best way over ones like loadstring(x)... although I would be happy with either, can't get either one to work. 我的代码有问题,我不知道是什么,我在网上搜索,_Gx方法被建议作为loadtring(x)之类的最佳方式...虽然我很满意,不能让任何一个工作。 What I want to do is, in ComputerCraft, send a function name and argument to a turtle, which I'm doing by saving both values to a table and sending across the table, and then on the turtle's program, have a big list of functions, and using a command, call them from the string sent and insert the arg as well. 我想要做的是,在ComputerCraft中,将函数名称和参数发送给乌龟,我正在通过将两个值保存到表并发送到表中,然后在乌龟的程序中,有一个大的列表函数,并使用命令,从发送的字符串中调用它们,并插入arg。 My error is "attempt to call nil", which I don't quite understand why it's saying that... Thanks in Advance! 我的错误是“试图打电话给零”,我不太明白为什么会这样说...在此先感谢!

EDIT 编辑

I've edited my code down, as asked, to show that even stripping all else away, this still fails. 正如我所要求的那样,我已经编辑了我的代码,以表明即使剥离所有其他东西,这仍然会失败。 I could even strip it down even more by taking the variable completely out, and putting the string straight into the _G. 我甚至可以通过将变量完全取出并将弦直接放入_G来进一步剥离它。 This still fails even doing it like that. 即使这样做也仍然失败。 I've decided to keep it in because that's how I am actually going to be using it later. 我决定保留它,因为这就是我以后实际使用它的方式。 Calling the function normally works fine. 调用该函数通常正常。 I'm using version Luaj-jse 2.0.3 我正在使用版本Luaj-jse 2.0.3

function foo ()
  print ("HI!")
end

print (_VERSION)

I don't know what rednet is, but it seems like you passes name of function to another Lua VM, which doesn't know anything about this function (this function is absent in that VM's globals table). 我不知道rednet是什么,但似乎你将函数名称传递给另一个Lua VM,它对该函数一无所知(该函数在该VM的全局表中不存在)。
So, passing function definition as string and executing it by receiver with loadstring is the only solution. 因此,将函数定义作为字符串传递并通过带有loadstring的接收器执行它是唯一的解决方案。

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

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