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
相关推荐
Jackson@ML7 小时前
在macOS上搭建C#集成开发环境指南
开发语言·macos·c#
井队Tell7 小时前
打造高清3D虚拟世界|零基础学习Unity HDRP高清渲染管线(第十天)
学习·3d·unity
月光双刀7 小时前
给旧版 .NET 也开一扇“私有之门”——ILAccess.Fody 实现原理与设计
c#·.net·fody·il·mono.cecil
张人玉7 小时前
WPF 静态样式与动态样式的定义及使用详解
ui·c#·wpf
山间点烟雨9 小时前
2. WPF程序打包成一个单独的exe文件
c#·wpf·独立打包exe
m0_7369270410 小时前
使用 Python 将 PowerPoint 转换为 Word 文档
java·开发语言·后端·职场和发展·c#
莫生灬灬10 小时前
[特殊字符] FBro工作流自动化平台 - 让浏览器自动化更简单
运维·chrome·c#·自动化
“抚琴”的人13 小时前
奥姆龙PLC与C#数据类型对应表
c#·上位机
fie888917 小时前
C#实现连续语音转文字
开发语言·c#