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",
  }

运行结果截图如下:
在这里插入图片描述

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