wren-lang / wren

The Wren Programming Language. Wren is a small, fast, class-based concurrent scripting language.
http://wren.io
MIT License
6.86k stars 550 forks source link

How can i stop wren script running? #1165

Open luodaoyi opened 1 year ago

luodaoyi commented 1 year ago

Like lua hook:

...
lua_sethook(luaVm, Lua_YeildHook, LUA_MASKLINE, 0);
....

void Lua_YeildHook(lua_State* _L, lua_Debug* ar)
{
    if (bStop) {
        lua_yield(_L, 0);
    }
}
CrazyInfin8 commented 1 year ago

I don't think there is currently a way to force a running wren script to terminate prematurely. However, in a fork I created, I hacked in a function to exit the VM here.

Essentially I added a new boolean value to the WrenVM struct called earlyExit which is checked each instruction cycle for the VM. If earlyExit was ever set to true while the VM is still executing code, it raises a runtime error. This way, in another thread, you can set this value (in my implementation using a function called wrenEarlyExit) to effectively stop the VM by the next instruction.

I don't know if this is actually the most optimal way to do this. You'll need another thread running to call the function to stop the VM. I haven't really tested to see whether this is thread safe to begin with, and I also don't know if stopping the VM prematurely might corrupt it or put it in an unusable state. From the few examples I've done with this, the VM seems to interpret and call functions afterwards without issue, though your mileage may vary.

luodaoyi commented 1 year ago

I don't think there is currently a way to force a running wren script to terminate prematurely. However, in a fork I created, I hacked in a function to exit the VM here.

Essentially I added a new boolean value to the WrenVM struct called earlyExit which is checked each instruction cycle for the VM. If earlyExit was ever set to true while the VM is still executing code, it raises a runtime error. This way, in another thread, you can set this value (in my implementation using a function called wrenEarlyExit) to effectively stop the VM by the next instruction.

I don't know if this is actually the most optimal way to do this. You'll need another thread running to call the function to stop the VM. I haven't really tested to see whether this is thread safe to begin with, and I also don't know if stopping the VM prematurely might corrupt it or put it in an unusable state. From the few examples I've done with this, the VM seems to interpret and call functions afterwards without issue, though your mileage may vary.

This solution is very good! but have to edit wren code ..

mhermier commented 1 year ago

From a callback it is not possible. From wren you can yield or abort.