using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
public class HW2 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//1.通过资源加载执行Lua程序
/TextAsset ta = Resources.Load
//print(ta);
LuaEnv env = new LuaEnv();
env.DoString(ta.text);
env.Dispose();
//2.通过require 'XXX'执行Lua程序
LuaEnv env = new LuaEnv();
env.DoString("require '面向对象实现'");
//访问Lua中的全局变量
/*int num = env.Global.Get<int>("num1");
print(num);
string s = env.Global.Get<string>("str");
print(s);
bool t = env.Global.Get<bool>("isOn");
print(t);*/
//env.Dispose();
//映射到类
/*Person p = env.Global.Get<Person>("person");//值拷贝,耗费性能,
print(p.name + "-" + p.age);
p.name = "ZZ";
env.DoString("print(person.name)");//不改变Lua中的变量值*/
//映射到接口
IPerson p = env.Global.Get<IPerson>("person");//引用拷贝,可改变Lua中的值
print(p.name + "-" + p.age);
p.name = "ZL";
env.DoString("print(person.name)");
env.Dispose();
}
//将Lua中的table映射到类(耗费性能)
class Person
{
public string name;
public int age;
}
//将Lua中的变量映射到接口
[CSharpCallLua]
interface IPerson
{
string name { get; set; }
int age { get; set; }
}
}
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using XLua;
public class Loader : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
LuaEnv env = new LuaEnv();
env.AddLoader(MyLoader);//先执行自定义的Loader,自定义Loader中有返回Lua程序时,将不再执行系统加载的Lua程序
env.DoString("require 'text01'");//加载的文件会传递给Lodader
env.Dispose();
}
//自定义Loader
private byte [] MyLoader(ref string filePath)
{
print(filePath);
//通过自定义Loader返回Lua程序
//string s = "print(123)";
//return System .Text .Encoding.UTF8 .GetBytes (s);
print(Application.streamingAssetsPath);
//通过路径读取返回Lua程序
string absPath = Application.streamingAssetsPath + "/" + filePath + ".lua.txt";
return System.Text.Encoding.UTF8.GetBytes(File.ReadAllText( absPath));
}
}