强制Lua脚本退出 [英] Forcing a Lua script to exit
问题描述
您如何结束长期运行的Lua脚本?
How do you end a long running Lua script?
我有两个线程,一个运行主程序,另一个控制用户提供的Lua脚本.我需要杀死正在运行Lua的线程,但是首先我需要退出脚本.
I have two threads, one runs the main program and the other controls a user supplied Lua script. I need to kill the thread that's running Lua, but first I need the script to exit.
是否有一种方法可以强制脚本退出?
Is there a way to force a script to exit?
我已经读到建议的方法是返回Lua异常.但是,不保证用户的脚本将永远调用api函数(它可能处于繁忙的循环中).此外,用户可以使用pcall
来防止错误导致脚本退出.
I have read that the suggested approach is to return a Lua exception. However, it's not garanteed that the user's script will ever call an api function ( it could be in a tight busy loop). Further, the user could prevent errors from causing his script to exit by using a pcall
.
推荐答案
您可以使用setjmp
和longjump
,就像Lua库在内部一样.这将使您摆脱pcalls
的困扰,而无需不断出错就可以了,这可以防止脚本尝试处理假错误并仍然使您无法执行. (我不知道这在线程中的表现如何.)
You could use setjmp
and longjump
, just like the Lua library does internally. That will get you out of pcalls
and stuff just fine without need to continuously error, preventing the script from attempting to handle your bogus errors and still getting you out of execution. (I have no idea how well this plays with threads though.)
#include <stdio.h>
#include <setjmp.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
jmp_buf place;
void hook(lua_State* L, lua_Debug *ar)
{
static int countdown = 10;
if (countdown > 0)
{
--countdown;
printf("countdown: %d!\n", countdown);
}
else
{
longjmp(place, 1);
}
}
int main(int argc, const char *argv[])
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
lua_sethook(L, hook, LUA_MASKCOUNT, 100);
if (setjmp(place) == 0)
luaL_dostring(L, "function test() pcall(test) print 'recursing' end pcall(test)");
lua_close(L);
printf("Done!");
return 0;
}
这篇关于强制Lua脚本退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!