xlua游戏热更新(C#访问lua)

xlua作为Unity资源热更新的重要解决方案api,在Tecent重多游戏中被采用,本文通过案例去讲解xlua代码结构层次。

csharp 复制代码
/*
 * Tencent is pleased to support the open source community by making xLua available.
 * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://opensource.org/licenses/MIT
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

using UnityEngine;
using XLua;

namespace XLuaTest
{
    public class Helloworld : MonoBehaviour
    {
        // Use this for initialization
        void Start()
        {
            //创建xlua虚拟机
            LuaEnv luaenv = new LuaEnv();
            luaenv.DoString("print('hello xlua!')");
            luaenv.DoString("CS.UnityEngine.Debug.Log('hello world')");
            //释放资源
            luaenv.Dispose();
        }

        // Update is called once per frame
    }
}

加载lua文件

Resources.Load("xlua/xx.lua") 加载

创建Resources 目录下xx.lua.txt文件

csharp 复制代码
//创建xlua虚拟机【建议全局唯一】
LuaEnv luaenv = new LuaEnv();
//加载lua脚本资源
TextAsset textAsset = Resources.Load<TextAsset>("xlua/hello.lua");
luaenv.DoString(textAsset.ToString());

loader加载

csharp 复制代码
luaenv.DoString("require 'xlua/hello'"); //require + 'lua文件名称不加扩展名'
//require 实际上是逐个查找loader文件 是否存在指定文件

自定义loader

挨个查找loader,若某个loader返回了字节数组,那么便不继续查找了

csharp 复制代码
  //加载loader
            luaenv.AddLoader(Myloader);
            
            luaenv.DoString("require 'xlua/hello'");
            //挨个查找loader,若某个loader返回了字节数组,那么便不继续查找了
            //释放资源
            luaenv.Dispose();

		/// <summary>
        /// 自定义loader
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private byte[] Myloader(ref string filePath)
        {
            print(filePath);
            string s = "print(123)";
            return Encoding.UTF8.GetBytes(s);
        }

构建Assets/StreamingAssets文件夹

csharp 复制代码
  private byte[] Myloader(ref string filePath)
        {
            //print(filePath);
            string absPath = Application.streamingAssetsPath + "/" + filePath + ".lua.txt";
            return Encoding.UTF8.GetBytes(File.ReadAllText(absPath));
        }

C#访问lua文件

全局变量

加载文件成功后,访问lua文件中的全局变量

--number 可以对应int float double

csharp 复制代码
           //通过luaenv 访问变量
            int integer_Lua = luaenv.Global.Get<int>("Integer");
            string name_Lua = luaenv.Global.Get<string>("Name");
            
            Debug.Log(integer_Lua + name_Lua);

csharp 复制代码
//lua文件中

person = {
    Name = "James",
    Sno = 23,
    
    eat = function()
        print("i'm eating!")
    end
    
}
//
//C#
class Person
        {
            public string _name;
            public int _sno;
        }
 Person luaPerson = luaenv.Global.Get<Person>("person");
            print(luaPerson._sno + ":" + luaPerson._name);

接口

csharp 复制代码
IPerson luaPerson = luaenv.Global.Get<IPerson>("person");
 print(luaPerson.sno + ":" + luaPerson.name);


[CSharpCallLua]
        interface IPerson
        {
            string name { get; set; }
            int sno { get; set; }
            void eat();
        }

字典

复制代码
dic = {
    china = 1,
    america = 2,
    uk  = 3,
}
csharp 复制代码
 //通过字典遍历
            Dictionary<string,int> dic =  luaenv.Global.Get<Dictionary<string, int>>("dic");
            foreach (var key in dic.Keys)
            {
                print(key + ":" + dic[key]);
            }

列表

复制代码
list = {'sdahjk',12,123,'12'}
csharp 复制代码
  //通过list访问
            List<object> list =  luaenv.Global.Get<List<object>>("list");
            foreach (var target in list)
            {
                print(target.ToString());
            }

再将上述数据通过List读取一次

LuaTable

csharp 复制代码
LuaTable table = luaenv.Global.Get<LuaTable>("person");
            table.Get<string>("name");

函数

csharp 复制代码
 [CSharpCallLua]
        delegate int Add(int a, int b);

//函数
            Add add = luaenv.Global.Get<Add>("add");
            print(add(3,5));
            add = null;

lua多返回值通过,out 变量接受

复制代码
add = function(a,b)
    return a + b,a,b
end
csharp 复制代码
 delegate int Add2(int a, int b, out int resa, out int resb);

使用LuaFunction (性能差)

csharp 复制代码
LuaFunction add = luaenv.Global.Get<LuaFunction>("add");
            object[] objects = add.Call(3, 5);
            print(objects[0]);
相关推荐
钢铁男儿19 分钟前
C# 表达式和运算符(表达式和字面量)
开发语言·c#
林鸿群1 小时前
C#子线程更新主线程UI及委托回调使用示例
开发语言·c#
o0向阳而生0o1 小时前
63、.NET 异常处理
c#·.net·异常处理
SteveDraw4 小时前
C++动态链接库封装,供C#/C++ 等编程语言使用——C++动态链接库概述(总)
开发语言·c++·c#·封装·动态链接库
Kookoos4 小时前
性能剖析:在 ABP 框架中集成 MiniProfiler 实现性能可视化诊断
后端·c#·.net·abp vnext·miniprofiler
阿翰6 小时前
自动 GitHub Readme 20 种语言翻译平台 - OpenAiTx 开源免费
c#·.net
枫叶kx10 小时前
1Panel运行的.net程序无法读取系统字体(因为使用了docker)
c#
军训猫猫头15 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
不爱写代码的玉子17 小时前
HALCON透视矩阵
人工智能·深度学习·线性代数·算法·计算机视觉·矩阵·c#
开开心心就好20 小时前
高效Excel合并拆分软件
开发语言·javascript·c#·ocr·排序算法·excel·最小二乘法