当前位置: 代码迷 >> 综合 >> lua遍历调用C#泛型List、IEnumberable、Dictionary
  详细解决方案

lua遍历调用C#泛型List、IEnumberable、Dictionary

热度:93   发布时间:2023-12-10 15:49:46.0

(补充:2016年11月3日 ,不要使用本文的方法,经测试会导致内存泄露。。原因是NewLuaTable方法会导致引用计数无法清除,无法正确的被lua虚拟机垃圾回收)


注:本文中使用的环境为Unity+lua

在使用lua的时候,我们经常需要调用遍历调用C#中的泛型结构(诸如List、IEnumberable、Dictionary)。在LUA中最通用的遍历方法是针对table的调用,所以我们可以将C#中的数据结构转换为lua table,然后作为参数传进lua中。

lua代码为

function test(k)for i,v in pairs(k) doDebug.Log(string.format("%d %s",i,v))end
end

我们传进来k为lua table,那么如何生成它的呢?

List<string> t = new List<string>(){
   "test1", "test2"};
LuaManager.Call ("test", t.toLuaTable());Dictionary<string,string> s = new Dictionary<string, string>();
s["321"]="123";
s["444"]="asetase";
LuaManager.Call ("test", s.toLuaTable());

LuaManager是我们封装的一个lua调用类,在后面会贴上代码。
我们给各个泛型集合增加了一个toLuaTable的方法

    public static class LuaTool{static public LuaTable CreateLuaTable(){return (LuaTable)LuaManager._lua.DoString("return {}")[0];}static public LuaTable CreateLuaTable(IEnumerable objs){var table = CreateLuaTable();int index = 0;foreach(var obj in objs){table[index.ToString()] = obj;index++;}return table;}static public LuaTable CreateLuaTable(IList objs){var table = CreateLuaTable();int index = 0;foreach(var obj in objs){table[index.ToString()] = obj;index++;}return table;}static public LuaTable CreateLuaTable(IDictionary objs){var table = CreateLuaTable();foreach(var key in objs.Keys){table[key] = objs[key];}return table;}public static LuaTable toLuaTable(this IEnumerable objs){return CreateLuaTable(objs);}public static LuaTable toLuaTable(this IList objs){return CreateLuaTable(objs);}public static LuaTable toLuaTable(this IDictionary objs){return CreateLuaTable(objs);}}

附LuaManager类代码

using System;
using LuaInterface;
using UnityEngine;using System.Collections;
using System.Collections.Generic;namespace JianghuX
{public static class LuaManager{static private string[] files = new string[]{
   "AttackLogic.lua", "BattleField.lua", "gongshi.lua", "MapUI.lua", "test.lua"};static private bool _inited = false;static public LuaScriptMgr _lua ;static public void Init(bool forceReset = false){if(forceReset) {_inited = false;if(_lua != null){_lua.Destroy();}}if(_inited) return;_lua = new LuaScriptMgr();_lua.Start ();foreach(var f in files){_lua.DoFile ("jianghux/" + f);}_inited = true;}static public object[] Call(string functionName , params object[] paras){if(!_inited){Init ();}var func = _lua.GetLuaFunction(functionName);if(func == null){Debug.LogError ("调用了未定义的lua 函数:" + functionName);return null;}else{return func.Call (paras);}}}
}
  相关解决方案