美文网首页
ToLua的Example示例学习笔记07_LuaThread

ToLua的Example示例学习笔记07_LuaThread

作者: 凌枫望星月 | 来源:发表于2020-05-11 15:45 被阅读0次

展示了如何使用lua线程。

1」代码

操作代码如下:

            function fib(n)
                local a, b = 0, 1
                while n > 0 do
                    a, b = b, a + b
                    n = n - 1
                end

                return a
            end

            function CoFunc(len)
                print('Coroutine started')                
                local i = 0
                for i = 0, len, 1 do                    
                    local flag = coroutine.yield(fib(i))    
                    print('flag = '..tostring(flag))
                    if not flag then
                        break
                    end                                      
                end
                print('Coroutine ended')
            end

            function Test()                
                local co = coroutine.create(CoFunc)                                
                return co
            end    

c#代码如下:

        new LuaResLoader();
        state = new LuaState();
        state.Start();
        state.LogGC = true;
        state.DoString(script);

        LuaFunction func = state.GetFunction("Test");
        func.BeginPCall();
        func.PCall();
        thread = func.CheckLuaThread();
        thread.name = "LuaThread";
        func.EndPCall();
        func.Dispose();
        func = null;

        thread.Resume(10);
        if (GUI.Button(new Rect(10, 50, 120, 40), "Resume Thead"))
        {
            int ret = -1;

            if (thread != null && thread.Resume(true, out ret) == (int)LuaThreadStatus.LUA_YIELD)
            {                
                Debugger.Log("lua yield: " + ret);
            }
        }
        else if (GUI.Button(new Rect(10, 150, 120, 40), "Close Thread"))
        {
            if (thread != null)
            {                
                thread.Dispose();                
                thread = null;
            }
        }

2」需要了解的部分

  • 与lua中的协程类似,local flag = coroutine.yield(fib(i))在第一次运行时暂停,然后Resume的时候从暂停的地儿继续前进,同时Resume传入的第一个参数就作为yield返回的值,例如每点击一次button, flag = true,第二个参数是out参数,传出之前yield的结果,这里就是斐波那契数列的值。

  • 还有一点,这里的C#取得协程对象的方式是调用Luaz中的Test函数取得,且让他启动的方式也是Resume(10),这里的10作为一开始启动的len传入。


3」值得注意的方法

  • LuaFunction.CheckLuaThread(); 返回一个LuaThread对象
  • LuaThread.Resume(T1(, out R1)) 第一次启动,T1为协程函数的参数,之后为传给yield()的值。R1为传出之前yield内部的结果。
  • 协程函数结束,协程自动结束。

相关文章

网友评论

      本文标题:ToLua的Example示例学习笔记07_LuaThread

      本文链接:https://www.haomeiwen.com/subject/ydmunhtx.html