3

I would like to call & await a C# async method from Lua / MoonSharp code.

For example:

1).

async void Test1() {
    await Something();
}

2).

async Task Test2() {
    await Something();
}

And then calling it from Lua - 1). does not await but continues script execution, and 2). throws ScriptRuntimeException: cannot convert clr type System.Threading.Tasks.Task`1[System.Threading.Tasks.VoidTaskResult] MoonSharp.Interpreter.Interop.Converters.ClrToScriptConversions.ObjectToDynValue exception.

Is there some way to make this work?

badevilerror
  • 113
  • 6
  • The converter probably does not know how to convert the state machine generated. What do you want to do in the end? You will likely need to do a synchronous block with `Something.Wait()` – Camilo Terevinto Jun 04 '18 at 19:47
  • @CamiloTerevinto I am making a simple mod system for Unity game. Some C# methods needs to be async (for example loading asset bundles - so to not block the rendering loop). And I need to call them from - in this case - mod's InitScript.lua (because game itself does not know much about what to load etc - the game just provides an api for Lua scripts. – badevilerror Jun 04 '18 at 19:55
  • @CamiloTerevinto i've also tried `Something.Wait()` as you mentioned, but no luck - it freezes entire Unity editor. – badevilerror Jun 04 '18 at 20:10

1 Answers1

3

I've finally gone with callbacks. I don't think it's a good solution, though. So if anyone have a better one i'll be more than happy to change the accepted answer.

For anyone interested here's how to make the callbacks work in MoonSharp:

Lua / MoonSharp

SomethingAsync(10, function()
    SomePrintFunction('async work done')
end)

C#

async void SomethingAsync(int whatever, DynValue callback) {
    await SomeAsyncWorkBeingDone();

    if (callback.Type == DataType.Function) {
        callback.Function.Call();
    }
}

More info can be found in the doc's.

badevilerror
  • 113
  • 6