Skip to content

LuaCoroutine ResumeAsync pushes wrong arguments on the stack #128

@CodeSmile-0000011110110111

Description

I've noticed I was getting the wrong arguments in my coroutine when using a custom StartCoroutine method that is supposed to take a LuaFunction, create a coroutine and resume it right away to closely model Unity coroutines:

private static readonly LuaFunction _startCoroutine = new(nameof(lunyscript_instance.StartCoroutine), async (context, buffer, ct) =>
{
  var instance = context.GetArgument<lunyscript_instance>(0);
  var function = context.GetArgument<LuaFunction>(1);
  
  var routine = new LuaCoroutine(function, true);
  var resultCount = await routine.ResumeAsync(context, buffer, ct);
  ...

I call it like so:
script.component:StartCoroutine(luaCoroutineWithArgs, 111, 222, 333)

I also tried changing my binding to this:

var instance = context.GetArgument<lunyscript_instance>(0);
var function = context.GetArgument<LuaFunction>(1);
var routine = new LuaCoroutine(function, true);
var args = NoArgs;

if (context.ArgumentCount > 2)
{
	args = new LuaValue[context.ArgumentCount - 2];
	context.Arguments.Slice(2).CopyTo(args);
}

var firstResults = await routine.ResumeAsync(context.State, args, ct);
for (int i = 0; i < firstResults.Length; i++)
	Debug.Log($"coroutine result[{i}] = {firstResults[i]}");

This calls a different overload of ResumeAsync.

Debugging this it seems that due to the "object" parameter (the object + the function + the three arguments) the resume method thinks I'm passing in a vararg because variableArgumentCount is 1.

var variableArgumentCount = Function.GetVariableArgumentCount(context.ArgumentCount - 1);

The Lua function signature:
function luaCoroutineWithArgs(arg1, arg2, arg3)

But the stack has 5 values. One function, three args, therefore 1 vararg is assumed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions