Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing a Lua script to exit

Tags:

lua

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.

like image 788
deft_code Avatar asked Aug 02 '11 14:08

deft_code


People also ask

How do I stop a Lua script?

Use os. exit() or just return from some "main" function if your script is embedded.

How do I return in Lua?

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.

Does return end in Lua?

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.

How do I close Lua Windows?

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.


1 Answers

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; } 
like image 152
Alex Avatar answered Nov 11 '22 16:11

Alex