WeaselGames / godot_luaAPI

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

Thread.yield_await & Signal metatable #92

Closed Trey2k closed 1 year ago

Trey2k commented 1 year ago

resolves #90

thread.yield_await():

This PR adds support to await in a GDScript function called by lua. To achieve this instead of passing a signal to await. you pass thread.yield_await() which takes a Array of args. All args are passed back to thread.resume() for you to handle as you wish. The next time thread.resume() is called the gdscript function will resume.

Since the lua state must yield, this is only available for lua threads. Currently calling the method from a normal lua state will caused undefined behavior.

Here is a example:

extends Node2D

var lua: LuaAPI
var thread: LuaThread

func wait_for_object():
    print("before")
    await thread.yield_await([get_tree().create_timer(3).timeout])
    print("after")
    return 1

func _ready():
    lua = LuaAPI.new()
    thread = LuaThread.new_thread(lua)
    thread.push_variant("WaitForObjectAsync", wait_for_object)
    thread.load_string("
    print(WaitForObjectAsync())
    ")

var yieldTime = 0
var timeSince = 0
func _process(delta):
    timeSince += delta.
    if thread.is_done() || timeSince <= yieldTime:
        return
    var ret = thread.resume()
    if ret is LuaError:
        print("ERROR %d: " % ret.type + ret.msg)
        return
    if ret:
        if ret[0] is Signal:
            set_process(false)
            await ret[0]
            yieldTime = 0
            timeSince = 1
            set_process(true)
            return
        yieldTime = ret[0]
        timeSince = 0

Other changes: