Skip to content

Instantly share code, notes, and snippets.

@starius
Created April 2, 2015 21:21
Show Gist options
  • Save starius/fa5227ce209c9bbc08b9 to your computer and use it in GitHub Desktop.
Save starius/fa5227ce209c9bbc08b9 to your computer and use it in GitHub Desktop.
How to interrupt running Lua
local x = 0
for i = 1, 10000000000 do
local y = getNumber() -- C function
x = x + y
end
print(x)
// 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");
}
}
}
@Fighter19
Copy link

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