日拱一卒,功不唐捐!Cn|

畅知

园龄:1年4个月粉丝:68关注:22

Lua热更学习--使用toLua中的协程

[6] C#访问调table类中的成员变量和函数

访问table中的变量和函数

lua中可以使用table作为class,因此对table中的函数访问调用是必要的根据前面对table访问和function的获取调用,这里尝试获取调用。

依然是如此,此种调用方式获取到的table中的函数是引用拷贝。

Main.lua脚本新增内容

CStudent = {
_name = "TonyChang",
_id = "202499990101",
_sex = "male",
CStudent = function()
print("table中的函数")
end
}

测试脚本中的调用内容:

//--------------------------------获取类类型table
LuaTable CStudent = CallLuaManager.Instance().LuaState.GetTable("CStudent");
//执行构造函数
CStudent.GetLuaFunction("CStudent").Call("TonyChang","男");
//打印结果
Debug.Log(CStudent["_name"]+" ," + CStudent["_id"] +" ," +CStudent["_sex"]);

使用toLua中的协程

lua中不支持协程,使用toLua中提供的协程方式来使用协程。

在使用协程之前,需要在管理类中添加LuaLooper组件,并将其LuaState与外部使用执行的LuaState虚拟机绑定。

LuaLooper luaLooper = gameObject.AddComponent<LuaLooper>();
// Debug.Log(gameObject.name);
luaLooper.luaState = _luaState;

Main.lua中的协程:

--使用toLua中提供的协程
--制作计时器
function Timer()
local t = 1
while t < 20 do
t = t + 1
coroutine.wait(1)
print(t)
end
StopTimer()
end
local coroutlineTimer = nil
function StartTimer()
print("run")
--开始协程时候传入类型为函数
coroutlineTimer = coroutine.start(Timer)
end
function StopTimer()
--传入要结束的协程
coroutine.stop(coroutlineTimer)
end

我们在C#测试脚本中开启协程:

//----------------------------------开始计时器
LuaFunction startTimer = CallLuaManager.Instance().LuaState.GetFunction("StartTimer");
startTimer.Call();
startTimer.Dispose();

image-20240512112431495

当然也可以传入参数设置计时时长:

image-20240512112758804

本文作者:畅知

本文链接:https://www.cnblogs.com/TonyCode/p/18187626

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   畅知  阅读(247)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起