Created
April 14, 2015 21:45
-
-
Save starius/4b83669609b329f31023 to your computer and use it in GitHub Desktop.
Interrupt and restart running Lua
This file contains 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
print('Lua script is running...') | |
local x = 0 | |
for i = 1, 10000000000 do | |
local y = getNumber() -- C function | |
x = x + y | |
end | |
print(x) |
This file contains 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> | |
enum { | |
STATE_NORMAL, | |
STATE_RESTART, | |
STATE_STOP | |
}; | |
int state = STATE_NORMAL; | |
int getNumber(lua_State* L) { | |
if (state != STATE_NORMAL) { | |
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 | |
while (state != STATE_STOP) { | |
state = STATE_NORMAL; | |
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"); | |
lua_close(L); | |
} | |
} | |
int main() { | |
std::srand(std::time(NULL)); | |
std::thread thread(luaRunner); | |
printf("Lua works in other thread\n"); | |
while (state != STATE_STOP) { | |
printf("Type 1 to restart Lua, 2 to stop Lua.\n"); | |
int input; | |
scanf("%d", &input); | |
if (input == 1) { | |
state = STATE_RESTART; | |
printf("Lua restarted!\n"); | |
} | |
if (input == 2) { | |
state = STATE_STOP; | |
printf("Lua stopped!\n"); | |
} | |
} | |
thread.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment