您的位置:首页 > 编程语言 > Lua

ToLua学习笔记(九) Example 09 Dictionary

2016-07-08 16:02 267 查看

ToLua学习笔记(九) Example 09 Dictionary

转载请注明出处四川包邮

ToLua学习笔记九 Example 09 Dictionary
代码

BindMap

这个例子主要演示的是lua中如何遍历访问c#的Dictionary类对象

这篇例子没什么需要讲的了,其实看看代码就明白用法了,不像之前的例子

代码

using UnityEngine;
using System.Collections.Generic;
using LuaInterface;

public class TestAccount
{
public int id;
public string name;
public int sex;

public TestAccount(int id, string name, int sex)
{
this.id = id;
this.name = name;
this.sex = sex;
}
}

public class UseDictionary : MonoBehaviour
{
Dictionary<int, TestAccount> map = new Dictionary<int, TestAccount>();

string script =
@"
function TestDict(map)
local iter = map:GetEnumerator()

--遍历
while iter:MoveNext() do
local v = iter.Current.Value
print('id: '..v.id ..' name: '..v.name..' sex: '..v.sex)
end
end
";

void Awake ()
{
map.Add(1, new TestAccount(2, "水水", 0));
map.Add(2, new TestAccount(1, "王伟", 1));
map.Add(3, new TestAccount(2, "王芳", 0));

LuaState luaState = new LuaState();
luaState.Start();
BindMap(luaState);

luaState.DoString(script);
LuaFunction func = luaState.GetFunction("TestDict");
func.BeginPCall();
func.Push(map);
func.PCall();
func.EndPCall();

func.Dispose();
func = null;
luaState.CheckTop();
luaState.Dispose();
luaState = null;
}

// 示例方式,正常导出无需手写下面代码
void BindMap(LuaState L)
{
L.BeginModule(null);
TestAccountWrap.Register(L);
L.BeginModule("System");
L.BeginModule("Collections");
L.BeginModule("Generic");
System_Collections_Generic_Dictionary_int_TestAccountWrap.Register(L);
System_Collections_Generic_KeyValuePair_int_TestAccountWrap.Register(L);
L.EndModule();
L.EndModule();
L.EndModule();
L.EndModule();
}
}


BindMap

代码中已经注明了这个函数是为了让例子能够独立运行,写的这个函数,其实正常开发的时候,并不需要执行它,而是在CustomSettings.cs里面的static BindType[] customTypeList ={…}添加即可.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  遍历 lua ToLua Unity