NLua icon indicating copy to clipboard operation
NLua copied to clipboard

Can't Create Coroutine From C#?

Open CannibalVox opened this issue 5 years ago • 3 comments

Hi, I'm trying to create coroutines for my methods so that all my scripts can make use of yield. However, it doesn't seem to be possible to call coroutine.create from C#? What's the correct way of working with coroutines?

using System;
using System.Diagnostics;
using System.Linq;
using NLua;

namespace CLuaTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Lua state = new Lua();
            state.DoString(@"
                function fib(n)
                    if n < 2 then 
                        return n
                    end
                    return fib(n - 2) + fib(n - 1);
                end
            ");
            var scriptFunc = state["fib"] as LuaFunction;
            var coroutine = state["coroutine"] as LuaTable;
            var create = coroutine["create"] as LuaFunction;
            var status = coroutine["status"] as LuaFunction;
            var co = create.Call(scriptFunc);
            if (co.Length == 1 && co[0] == null)
            {
                Console.WriteLine("wat da heck");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("ok all good");
            Console.ReadKey();
        }
    }
}

CannibalVox avatar Sep 08 '19 02:09 CannibalVox

Hi @CannibalVox Is there any reason why you can't create from Lua code DoString("corountine.create(...)"); ?

viniciusjarina avatar Sep 13 '19 22:09 viniciusjarina

Same results:

using System.Diagnostics;
using System.Linq;
using NLua;

namespace CLuaTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Lua state = new Lua();
            state.DoString(@"
                function fib(n)
                    if n < 2 then 
                        return n
                    end
                    return fib(n - 2) + fib(n - 1);
                end

                out = coroutine.create(fib)
            ");
            var co = state["out"];
            if (co == null)
            {
                Console.WriteLine("wat da heck");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("ok all good");
            Console.ReadKey();
        }
    }
}

CannibalVox avatar Sep 13 '19 22:09 CannibalVox

As for why I'm trying to pull the coroutine out, I'd like to run a node-style message pump where I hold a coroutine for every currently-executing script and cycle through them resuming them each in turn

CannibalVox avatar Sep 13 '19 22:09 CannibalVox