How do you end a long running Lua script?
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?
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
.
Use os. exit() or just return from some "main" function if your script is embedded.
Function return values In most languages, functions always return one value. To use this, put comma-separated values after the return keyword: > f = function () >> return "x", "y", "z" -- return 3 values >> end > a, b, c, d = f() -- assign the 3 values to 4 variables.
There is an implicit return at the end of the Lua functions. As per syntactic reason the return statement should be the last statement of a block or function, before the end keyword.
Try control-D in Unix, control-Z in Windows or os. exit() if you must. I've found one situation where only os. exit() works: the interactive lua shell of the lua.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With