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");
}
}
}
@etorth
Copy link

etorth commented Aug 6, 2019

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

@starius
Copy link
Author

starius commented Aug 6, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment