逐行执行Lua脚本时检测代码块
这听起来像是一个愚蠢的问题,但我看不到任何地方提到这个特定问题。基本上:
我想逐行执行Lua脚本,主要是为了能够随时随地暂停/恢复执行。我所做的很简单:使用 luaL_loadbuffer() 加载一个块,然后发出 lua_pcall()。
问题是...我怎样才能正确检测 Lua 块以便以原子方式执行它们?
例如,假设脚本中有一个函数 - 通过使用上述方法逐行执行文件,我似乎无法正确识别该函数,因此其内容被加载并调用一个一个。
我可以想象,一种解决方案是手动处理一个堆栈,在该堆栈中我推送我可以在脚本中识别的控制关键字(“function”、“if”、“do”等)以及它们相应的“end”子句(如果我发现嵌套)块。一旦我推动了最后的“结束”,我就会调用整个块,但这听起来很糟糕。当然必须有更好的方法来做到这一点。
希望它有意义,谢谢!
This may sound like a silly question but I could see no mention anywhere of this particular problem. Basically:
I want to execute a Lua script line by line, primarily to have the ability to pause/resume execution anytime and anywhere I want. What I do is simple: load a chunk with luaL_loadbuffer() and then issue a lua_pcall().
Thing is... How can I properly detect Lua blocks in order to execute them atomically?
For instance, suppose there's a function in the script -- by executing the file line by line with the method described above, I can't seem to have a way to properly recognize the function, and in consequence its contents are loaded and called one by one.
I can imagine that one solution would be to manually handle a stack where I push control keywords I can recognize in the script ("function", "if", "do", etc) and their corresponding "end" clause if I find nested blocks. Once I push the final "end" I call the entire block, but that sounds simply awful. Surely there must be a better way of doing this.
Hope it makes some sense, and thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请查看 Lua 协程 来实现为游戏实体编写脚本的功能。这个想法是在 sleep() 和 waitforevent( )您提到的例程,然后稍后恢复(例如超时后或事件发生)。
Please take a look at Lua coroutines to implement that functionality for scripting game entities. The idea is to yield the coroutine in the sleep() and waitforevent() routines you mentioned, and then resume later (e.g. after a timeout or event occurs).
使用lua_sethook()。
请注意,您可能确实想尝试一下您需要的确切钩子调用粒度。我建议改为执行字节码指令块。一行很长的行可能包含许多指令。
Use lua_sethook().
Note that you probably do want to experiment with what exact hook call granularity you need. I'd recommend executing chunks of bytecode instructions instead. One really long line may contain many instructions.