逐行执行Lua脚本时检测代码块

发布于 2024-10-25 16:54:05 字数 416 浏览 4 评论 0原文

这听起来像是一个愚蠢的问题,但我看不到任何地方提到这个特定问题。基本上:

我想逐行执行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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

篱下浅笙歌 2024-11-01 16:54:05

请查看 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).

内心激荡 2024-11-01 16:54:05

使用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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文