c#调Lua返回个字符串

环境:

使用xlua,腾讯github仓库直接导入,添加即可

用途:

利用热更特性,内嵌lua代码,方便对于不同项目,不同类型数据进行动态数据信息配置,这样就不用在c#中声明对应的类了

关键部分代码如下:

c#部分代码如下

cs 复制代码
    //传入读取的字符
    TXRameTime(_strPath[0]);

    
    private XLua.LuaEnv luaEnv;
    //对应功能类
    void TXRameTime(string jsonStr)
    {
         luaEnv = new XLua.LuaEnv();
        //luaEnv.DoString("CS.UnityEngine.Debug.Log('hello world')");
        luaEnv.DoString("require 'Lua.Read'");

        string result =ParseJsonFromLua(jsonStr);
        if (!string.IsNullOrEmpty(result))
        {
            Debug.Log("Lua 返回的处理后字符串:\n" + result);
        }
        
        
        luaEnv.Dispose();
    }

    /// <summary>
    /// 调用 Lua 解析 JSON
    /// </summary>
    private string ParseJsonFromLua(string inputJson)
    {
        try
        {
            // 获取 Lua 函数
            LuaFunction luaFunc = luaEnv.Global.Get<LuaFunction>("parse_json");
            if (luaFunc == null)
            {
                Debug.LogError("未找到 Lua 函数 parse_json");
                return null;
            }

            // 调用 Lua 函数,获取返回值(多返回值用 object[] 接收)
            object[] returns = luaFunc.Call(inputJson);
            

            // 解析返回值(Lua 函数返回 (result_str, error_msg))
            if (returns != null && returns.Length >= 2)
            {
                string resultStr = returns[0] as string; // 第一个返回值:处理后的字符串
                string errorMsg = returns[1] as string;  // 第二个返回值:错误信息

                if (resultStr != null)
                {
                    return resultStr; // 返回成功结果
                }
                else
                {
                    Debug.LogError("Lua 处理失败:" + errorMsg);
                    return null;
                }
            }
            else
            {
                Debug.LogError("Lua 函数返回值格式错误");
                return null;
            }
        }
        catch (Exception e)
        {
            Debug.LogError("调用 Lua 函数异常:" + e.Message);
            return null;
        }
    }
    
    
    private void OnDestroy()
    {
        // 释放 Lua 环境(必须手动释放,否则内存泄漏)
        if (luaEnv != null)
        {
            luaEnv.Dispose();
        }
    }

Lua代码如下:

Lua 复制代码
--这里需要引入dkjson库,网上有自己搜下吧,然后把代码放在与lua文件同目录下
--或lua常用目录下,能引用到就行
local dkjson = require("Lua.dkjson")

function parse_json(json_str)
    -- 空输入检查
    if not json_str or json_str == "" then
        return nil, "空的 JSON 字符串"
    end

    -- 解析 JSON
    local ok, result = pcall(dkjson.decode, json_str)
    if not ok or type(result) ~= "table" then
        return nil, "解析失败:" .. tostring(result)
    end

    -- 修正:先检查 WeiXing 是否为数组(原代码逻辑顺序错误)
    if not result.Data or not result.Data.WeiXing or type(result.Data.WeiXing) ~= "table" then
        return nil, "字段缺失:Data.WeiXing 不存在或非数组"
    end

    -- 提取所有 datetime
    local datetimeList = {}
    for i, item in ipairs(result.Data.WeiXing) do
        if item.datetime then
            table.insert(datetimeList, item.datetime)
        else
            print(string.format("警告:第 %d 个 WeiXing 元素缺少 datetime 字段,已跳过", i))
        end
    end

    -- 检查是否有有效数据
    if #datetimeList == 0 then
        return nil, "WeiXing 数组中无有效的 datetime 数据"
    end

    -- 修正:Lua 数组索引从 1 开始(原代码用了 0 导致取空)
    local successData = { datetime = datetimeList[1] }  -- 取第一个元素的 datetime

    local jsonResult, encodeErr = dkjson.encode(successData)
    if encodeErr then
        return nil, "序列化结果失败:" .. encodeErr
    end
    return jsonResult, nil
end

function to_json(lua_table)
    if not lua_table then
        return nil, "空的 Lua 表"
    end
    local ok, result = pcall(dkjson.encode, lua_table)
    if not ok then
        return nil, "序列化失败:" .. result
    end
    return result, nil
end
相关推荐
xiaoshuaishuai81 小时前
C# AI实现PR处理、单元测试
开发语言·c#·log4j
LONGZHIQIN1 小时前
C#基础复习笔记
开发语言·笔记·c#
品尚公益团队4 小时前
C#在asp.net网页开发中的带cookie登录实现
前端·c#·asp.net
吴可可1234 小时前
C#自定义CAD多段线零件实体
c#
CallmeFoureyes4 小时前
使用 C# 提取 Word 文档中的表格数据
开发语言·c#·word
思麟呀4 小时前
在C++基础上理解CSharp-7
java·jvm·c++·c#
杰佛史彦明16 小时前
ElasticSearch中的分词器详解
大数据·elasticsearch·c#
czhc11400756637 小时前
710:CT分辨率;BGA;DBC;[ObservableProperty],[Required]
c#
我才是银古8 小时前
当 GIS 开发遇上 .NET:一个 GDAL 集成工具库的架构设计与实践
c#·gis·gdal
丁小未8 小时前
基于MVVM框架的XUUI 扩展的UI管理系统教程
unity·mvvm·ui框架·xuui·ui管理器