How can I end a Lua thread cleanly?(如何干净地结束 Lua 线程?)
问题描述
我的情况是我使用 Lua (C) API 来执行保存在字符串中的脚本.我希望用户能够终止脚本的执行(如果脚本包含无限循环,这是必不可少的),我该怎么做?
My situation is that I'm using the Lua (C) API to execute a script held in a string. I would like the user to be able to terminate the execution of the script (this is essential if the script contains an infinite loop), how can I do this?
lua_State *Lua = lua_open();
char * code;
// Initialisation code
luaL_dostring(L, code);
推荐答案
你可以使用钩子在每次 lua 执行一行脚本时回调到 C.在这个钩子函数中,你可以检查用户是否想退出,如果他们想退出就调用 lua_error.
You can use a hook to callback to C every time lua executes a line of the script. In this hook function you can check if the user wanted to quit, and call lua_error if they did.
static bool ms_quit = false;
void IWantToQuit()
{
ms_quit = true;
}
void LineHookFunc(lua_State *L, lua_Debug *ar)
{
if(ar.event == LUA_HOOKLINE)
if(ms_quit == true)
luaL_error(L, "Too Many Lines Error");
}
//...
lua_State *Lua = lua_open();
char * code;
// Initialisation code
lua_sethook(Lua, &LineHookFunc, LUA_MASKLINE, 0);
luaL_dostring(L, code);
这篇关于如何干净地结束 Lua 线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何干净地结束 Lua 线程?


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01