Created
April 2, 2015 21:21
-
-
Save starius/fa5227ce209c9bbc08b9 to your computer and use it in GitHub Desktop.
How to interrupt running Lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local x = 0 | |
for i = 1, 10000000000 do | |
local y = getNumber() -- C function | |
x = x + y | |
end | |
print(x) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// C++11 | |
// Compile on Debian Wheezy: | |
// g++ -std=c++11 wrapper.cpp -o wrapper.exe \ | |
// -llua5.1 -I /usr/include/lua5.1/ -pthread | |
#include <cstdlib> | |
#include <cstdio> | |
#include <ctime> | |
#include <thread> | |
#include <lua.hpp> | |
bool stop_lua = false; | |
int getNumber(lua_State* L) { | |
if (stop_lua) { | |
return luaL_error(L, "Interrupted"); | |
} | |
// return random number | |
int value = std::rand(); | |
lua_pushinteger(L, value); | |
return 1; | |
} | |
void luaRunner() { | |
// this code is run in other thread | |
lua_State* L = luaL_newstate(); | |
luaL_openlibs(L); | |
// bind function getGlobal | |
lua_pushcfunction(L, getNumber); | |
lua_setglobal(L, "getNumber"); | |
// run script.lua | |
int error = luaL_dofile(L, "script.lua"); | |
} | |
int main() { | |
std::srand(std::time(NULL)); | |
std::thread thread(luaRunner); | |
printf("Lua works in other thread\n"); | |
while (true) { | |
printf("Type 123 to interrupt Lua.\n"); | |
int input; | |
scanf("%d", &input); | |
if (input == 123) { | |
stop_lua = true; | |
printf("Lua stopped!.\n"); | |
} | |
} | |
} |
nice code.
Question from a new lua coder: this code can interrupt the lua executor and stop the program.
Does lua support to interrupt lua, save the lua state, then we restore lua exactly at the point where last time it get inpterrupted?Thanks,
etorth
Hey etorth
Yes it does, through yield. It has to be cooperative rather than preemptive anyway.
Boris
Nice idea!
But as a side-note for other readers signaling another thread this way is unsafe (it's not guaranteed that stop_lua will ever read the changed value in the "luaRunner" thread, for example, because CPU caches are never synchronized).
The simplest way would be using an std::atomic.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice code.
Question from a new lua coder: this code can interrupt the lua executor and stop the program.
Does lua support to interrupt lua, save the lua state, then we restore lua exactly at the point where last time it get inpterrupted?
Thanks,
etorth