xlua-C#訪問lua中的table

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
/*
 * Author:W
 * C#訪問Lua中table
 */
public class CSharpCallLua : MonoBehaviour {

	private LuaEnv luaEnv;
	// Use this for initialization
	void Start () {
		luaEnv = new LuaEnv();

		luaEnv.DoString("require 'CSharpCallLua'");

		//方式1:通過映射類或結構體訪問lua中的table
		//特點:通過值拷貝的形式,因此會比較耗費性能;另外,各自修改值,不會影響到對方
		Student student = luaEnv.Global.Get<Student>("Student");
		Debug.Log("方式1 普通類或結構體:Name=" + student.Name + " Age=" + student.Age);

		Debug.Log("===================================================");

		//方式2:通過接口訪問lua中的table
		//特點:類似引用的方式,因此在C#中做修改,也會影響到lua中變量值
		IStudent student1 = luaEnv.Global.Get<IStudent>("Student");
		Debug.Log("方式2 接口:Name="+student1.Name+" Age="+student1.Age);
		student1.sum(1, 4);
		student1.sum2(5, 6);
		student1.sum3(7, 8);

		Debug.Log("===================================================");

		//方式3:通過Dictionary/List訪問lua中的table
		//Dictionary只能訪問到“key = value”的		
		Dictionary<string, object> Dict = luaEnv.Global.Get<Dictionary<string, object>>("DictAndList");
		foreach (string key in Dict.Keys)
		{
			Debug.Log("方式3:Dict字典="+ key+"-"+Dict[key]);
		}
		//List只能訪問到只有value的
		List<object> Lists = luaEnv.Global.Get<List<object>>("DictAndList");
		foreach (object o in Lists)
		{
			Debug.Log("方式3:List集合= "+ o);
		}

		Debug.Log("===================================================");

		//方式4:使用xlua自帶通用luaTable映射類來訪問lua中的table
		//特點:不需要生成代碼,但是慢,比方式2慢一個數量級,不推薦使用
		LuaTable luaTable = luaEnv.Global.Get<LuaTable>("Student");
		Debug.Log("方式4:LuaTabel類= Name-" +luaTable.Get<string>("Name")) ;


	}

	private void OnDestroy()
	{
		if (luaEnv != null)
			luaEnv.Dispose();
	}

	/// <summary>
	/// 對應的映射類
	/// </summary>
	class Student
	{
		public string Name;
		public int Age;
	}
	
}


/// <summary>
/// 對應的接口
/// 注意:必須加上[CSharpCallLua]標籤
/// </summary>
[CSharpCallLua]
interface IStudent
{
	string Name { get; set; }
	int Age { get; set; }

	void sum(int a,int b);
	void sum2(int a, int b);

	void sum3(int a, int b);

}

lua腳本

Student =
{ Name="WangLunQiang",
  Age=35,
  --函數定義方式1
  sum = function(self,a,b)
    print("sum = ",a+b)
  end
  }
  --函數定義方式2:使用冒號,自動會賦值self
  function Student:sum2(a,b)
    print("sum2 = ",a+b)
  end
  
  --函數定義方式3;使用點,需要傳入self自身參數
  function Student.sum3(self,a,b)
    print("sum3 = ",a+b)
  end
  
  DictAndList = {
    Name="WangLunQiang",
    Age=35,
	eat = function()
	  print("eat")
	end,
	2,
	4,
	"W",
  }

運行結果截圖如下:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章