XLua常见问题汇总(持续更新)

这里记录下自己潜伏在XLua官方群中,看见大家发的一些常见问题,利人利己,嘿嘿,发现新的好的问题就会及时更新上来。


1.热更函数时,函数体内StartCoroutine的调用

例如,我们C#函数如下:
using UnityEngine;
using System.Collections;

namespace MyExamples {
    [XLua.Hotfix]
    public class Hotfix : MonoBehaviour {
        int i = 0;

        void Show() {
            Debug.Log("Show!!!");
            StartCoroutine(ie());
        }

        IEnumerator ie() {
            while(i < 5) {
                Debug.Log("ie   " + i);
                i++;
                yield return null;
            }
        }
    }
}

我们要用XLua来重写这个方法应该怎么写呢,如下即可

xlua.private_accessible(CS.MyExamples.Hotfix);  

xlua.hotfix(CS.MyExamples.Hotfix, "Show", function(self)  
    print("lua---Show");
    self:StartCoroutine(self:ie());
end)

2.热更函数时,给UGUI绑定事件,btn.onClick.AddListener();

我们在Lua中,将触发的事件函数封装到一个function中,如下
xlua.hotfix(CS.MyExamples.Hotfix, "Show", function(self)  
    self.btn.onClick:AddListener(function()
        self:onClick();
    end);
end)

然后别忘了给Button和UnityEngine.Events.UnityEvent添加[LuaCallCSharp]白名单。


3.Lua中,用pcall()和xpcall()代替c#的try{}catch{}

也有很多人问,怎么在lua中实现C#的trycatch,Lua中我们可以用自带的基础函数pcall或xpcall来替代,下面是Lua5.3对应的函数说明

pcall (f [, arg1, ···])
传入参数,以 保护模式 调用函数 f 。 这意味着 f 中的任何错误不会抛出; 取而代之的是,pcall 会将错误捕获到,并返回一个状态码。 第一个返回值是状态码(一个布尔量), 当没有错误时,其为真。 此时,pcall 同样会在状态码后返回所有调用的结果。 在有错误时,pcall 返回 false 加错误消息。

xpcall (f, msgh [, arg1, ···])
这个函数和 pcall 类似。 不过它可以额外设置一个消息处理器 msgh。

直接举例子,将下面C#的转换成Lua语言:
try {
    int.Parse("s");
} catch {
    Debug.Log("error");
}
pcall:
local s = "ss";
local result, intValue = pcall(function()
	return CS.System.Int32.Parse(s)
end);

--若s="ss",result为false,intValue为报错信息c# exception:Input string was not in the correct format,stack:  at System.Int32.Parse...
--若s="11",result为true,intValue为对应的返回值11

if result then
	print("suc");
	print(result);
	print(intValue);
else
	print("fail");
	print(result);
	print(intValue);
end
xpcall:
local s = "11";
local result, intValue = xpcall(function()
	return CS.System.Int32.Parse(s)
end,	function()
	--前面的方法执行失败才会走进来
	print("fail		handle");
end);

--若s="ss",result为false,intValue为nil
--若s="11",result为true,intValue为对应的返回值11

if result then
	print("suc");
	print(result);
	print(intValue);
else
	print("fail");
	print(result);
	print(intValue);
end




猜你喜欢

转载自blog.csdn.net/wangjiangrong/article/details/80584165
今日推荐