toLua学习笔记十二——调用c#中的数组、列表和字典

17 篇文章 4 订阅

数组

首先在c#脚本中创建一个数组

public class Lesson{
    public int[] array = new int[5]{1,2,3,4,5};
}

在CustomSettings文件中添加Lesson类并生成,不然会识别不到
在lua中创建一个变量接收Lesson类

local obj = Lesson()

数组的长度

obj.array.Length

访问数组中的元素

直接用下标索引即可

obj.array[0]

查找元素的位置

obj.array:IndexOf(2)

遍历数组

1、直接遍历,注意lua中的遍历是从1开始,但是数组是c#中的结构,规则应该和c#一致,要从0开始

for i = 0, obj.array.Length - 1 do
    print("array:"..obj.array[i])
end

2、迭代器遍历

local iter = obj.array:GetEnumerator()
while iter:MoveNext() do
    print("iter:"..iter.Current)
end

3、将数组转成table再遍历

local t = obj.array:ToTable()
for i = 1, #t do
    print("table:"..t[i])
end

创建数组

需要注意的是这里System.Int32会识别不到,要将它添加到CustomSettings中并生成

local array2 = System.Array.CreateInstance(typeof(System.Int32),10)
print(array2.Length)
print(array2[0])
array2[0]=99
print(array2[0])

列表

首先在c#脚本中创建一个list,需要注意的是,虽然前面我们已经将Lesson类添加到customsettings中,但是现在改变了这个类,就必须在菜单栏重新生成一次

 public List<int> list = new List<int>();

添加元素

List中所有成员函数都可以通过 :函数名 的方式来调用

obj.list:Add(1)

获取元素

obj.list[0]

得到List的长度

obj.list.Count

遍历

for i = 0, obj.list.Count - 1 do
    print("遍历:"..obj.list[i])
end

在lua中创建一个c#的list

这里需要注意一点,tolua对于泛型的支持不太好,想要用什么泛型类型的对象,都需要在customSettings中去添加对应类然后生成,添加形式为类名<泛型类型>。
比如想要使用string类型的List,写法如下

_GT(typeof(List<string>)),

生成之后才能在tolua中使用,在tolua中,list的泛型写法为List_泛型类型

local list2 = System.Collections.Generic.List_string()
list2:Add("123")
print(list2[0])

字典

在c#脚本中创建一个字典

public Dictionary<int,string> dic = new Dictionary<int, string>();

添加元素

和List一样,字典中所有成员函数都可以通过 :函数名 的方式来访问

obj.dic:Add(1,"123")
obj.dic:Add(2,"234")
obj.dic:Add(3,"345")

遍历

需要注意的是tolua不支持通过pairs来遍历字典,需要使用迭代器遍历
1、遍历键和值

local iter = obj.dic:GetEnumerator()
while iter:MoveNext() do
    local v = iter.Current
    print(v.Key .."_".. v.Value)
end

2、遍历键

local keyIter = obj.dic.Keys:GetEnumerator()
while keyIter:MoveNext() do
        print("key:"..keyIter.Current)
end

3、遍历值

local valueIter = obj.dic.Values:GetEnumerator()
while valueIter:MoveNext() do
        print("value:"..valueIter.Current)
end

创建字典

和List一样,如果要在tolua中创建字典对象,需要将其泛型类型添加到customsettings中
tolua中字典的泛型同样使用_来分隔,格式为Dictionary_键类型_值类型

local dic2 = System.Collections.Generic.Dictionary_int_string()
dic2:Add(10,"123")

local dic3 = System.Collections.Generic.Dictionary_string_int()
dic3:Add("123",88888)

访问元素

一般类型可以直接通过键来访问

print(dic2[10])

但是stirng类型不能够直接通过字符串作为键类访问值,需要使用c#中的方法

local b,v = dic3:TryGetValue("123",nil)
print(v)
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值