WeaselGames / godot_luaAPI

Godot LuaAPI
https://luaapi.weaselgames.info
Other
371 stars 28 forks source link

Create interrupt_execution and kill methods on LuaCoroutine #112

Closed RadiantUwU closed 1 year ago

RadiantUwU commented 1 year ago

Already documented:

interrupt_execution() will throw an error execution interrupted

kill() will throw an error execution terminated and will not stop until the thread exits all the way to the top stack.

RadiantUwU commented 1 year ago

Added the checks. It will remove the hook after it exits the resume call.

RadiantUwU commented 1 year ago

extends Node

var lua: LuaAPI
var coroutine: LuaCoroutine
const killSec := 10

func _ready():
    lua = LuaAPI.new()
    coroutine = lua.new_coroutine()
    coroutine.load_string("
    i = 0
    while true do
        pcall(function() while true do i = i + 1 end end)
    end
    ")

var running := false
var timeRunning := 0.0
var thread := Thread.new()
func _process(delta):
    if not running:
        thread.start(_thread)
        running = true
    else:
        timeRunning += delta
        if timeRunning >= 2*killSec and thread.is_started():
            coroutine.kill()
            thread.wait_to_finish()
            timeRunning = 0
        elif timeRunning >=killSec and thread.is_started():
            coroutine.interrupt_execution()

func _thread():
    print("Start")
    var ret = coroutine.resume()
    running=false
    if ret is LuaError:
        print("ERROR %d: " % ret.type + ret.msg)
        return
    print("Killed")```
Trey2k commented 1 year ago

Tested and confirmed to work with the following script

extends Node

var lua: LuaAPI
var coroutine: LuaCoroutine
const killSec := 10

func _ready():
    lua = LuaAPI.new()
    lua.bind_libraries(["base"])
    coroutine = lua.new_coroutine()
    var err = coroutine.load_string("
    i = 0
    while true do
        pcall(function() while true do i = i + 1 end end)
    end
    ")
    if err is LuaError:
        print("ERROR %d: " % err.type + err.message)

var running := false
var timeRunning := 0.0
var thread := Thread.new()
var tried_interrupt := false
func _process(delta):
    if not running:
        thread.start(_thread)
        running = true
    else:
        timeRunning += delta
        if timeRunning >= 2*killSec and thread.is_started():
            coroutine.kill()
            thread.wait_to_finish()
            timeRunning = 0
        elif timeRunning >=killSec and thread.is_started() and not tried_interrupt:
            coroutine.interrupt_execution()
            tried_interrupt = true

func _thread():
    print("Start")
    var ret = coroutine.resume()
    running=false
    if ret is LuaError:
        print("ERROR %d: " % ret.type + ret.message)
        return
    print("Killed")