I'm using NLua to run Lua script in my app. I need to implement ability to terminate script that runs in separate thread at any time, for example user press "Stop" button and script must terminate immediately. I've read about SetDebugHook and tried to Close Lua State and call Error on state, but I always get AccessViolationException.
I've tried
Lua env = new Lua(); // created in main thread
env.DoString(); // called in second thread
// Called in main thread
public void Stop()
{
env.Close(); // Didn't work. AccessViolationException
env.State.Close(); // Didn't work. AccessViolationException
env.State.Error("err"); // Didn't work. AccessViolationException
}
Tried to synchronize threads with lock
lock (locker)
{
if (env.IsExecuting)
env.Close();
}
Same issue. AccessViolationException
Thanks.
This method works reasonably well, using the
lua_sethookto check for signal to abort before executing each line of lua code:this ofcourse comes at the cost of some added overhead for every line, to reduce that you can change the hook one of the other values.
Another option is to use tokens that the lua thread would watch and then abort as needed, this method does require some handling within the lua script:
Now often your lua execution will be more complex, containing many nested loops, and in those cases you can implement a function in lua to check the tokens and throw an error when the token is true:
with that loaded into the lua state we should make some changes to the
DoLuafunction: