Unity ToLua 之 Lua调用C#(二)

Unity ToLua 之 Lua调用C#(二)

一.ToLua调用C#中的List和Dictionary

  • 注意List和dictionary对应的泛型需要先填写到CustomSetting中,然后生成
  • XLua 中遍历Dictionary可以使用Pairs,但是ToLua中只能使用迭代器
  • ToLua中当使用string为Key时不能通过[]来直接访问对应的Value
public class TestListAndDic
{
    public List<string> lst = new List<string>(){"zzs","wy","lzq"};
    public Dictionary<int,string> dic = new Dictionary<int, string>()
    {
        {1,"zzs"},
        {2,"wy"},
        {3,"lzq"}
    };
}
--List
local a = TestListAndDic()
for i = 0, a.lst.Count - 1 do
    print(a.lst[i])
end

local list = System.Collections.Generic.List_string()
list:Add("zzs")
print(list[0])
local list2 = System.Collections.Generic.List_int()
list2:Add(999)
print(list2[0])


--Dic
--XLua 中遍历Dictionary可以使用Pairs,但是ToLua中只能使用迭代器
local iter = a.dic:GetEnumerator()
while iter:MoveNext() do
    local v = iter.Current
    print(v.Key.."_"..v.Value)
end 

local dic1 = System.Collections.Generic.Dictionary_int_string()
dic1:Add(1,"zzs")
print(dic1[1])

--ToLua中当使用string为Key时不能通过[]来直接访问对应的Value
local dic2 = System.Collections.Generic.Dictionary_string_int()
dic2:Add("zzs",1)
local b,val = dic2:TryGetValue("zzs",nil)
print(val)

在这里插入图片描述

二.ToLua调用C#中的拓展方法

  • 拓展方法需要在CustomSettings进行添加绑定
public static class PersonExt
{
    public static void Play(this Person person)
    {
        Debug.Log(person.name+"玩");
    }
}
public class Person
{
    public string name = "zzs";
    public void Eat()
    {
        Debug.Log(name+"吃饭");
    }
}
local p = Person()
p:Eat()
p:Play()

在这里插入图片描述

三.ToLua调用C# ref,out参数的函数

  • 和XLua非常相似
  • Out参数的时候不能直接省略不写
public class Lesson06
{
    public int RefFunc(int a, ref int b, ref int c, int d)
    {
        b = a + d;
        c = a - d;
        return 100;
    }

    public int OutFunc(int a, out int b, out int c, int d)
    {
        b = a + d;
        c = a - d;
        return 200;
    }

    public int RefAndOutFunc(int a, ref int b, out int c, int d)
    {
        b = a + d;
        c = a - d;
        return 300;
    }
}

--和XLua非常相似
local a = Lesson06()
local a1,a2,a3 = a:RefFunc(10,0,0,1);
print(a1,a2,a3)
--在Out参数的时候不能直接省略不写
local b1,b2,b3 = a:OutFunc(10,nil,nil,1);
print(b1,b2,b3)
local c1,c2,c3 = a:RefAndOutFunc(10,0,nil,1);
print(c1,c2,c3)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值