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
相关推荐
云草桑24 分钟前
.net AI开发04 第八章 引入RAG知识库与文档管理核心能力及事件总线
数据库·人工智能·microsoft·c#·asp.net·.net·rag
Sator12 小时前
Unity烘焙光打包后光照丢失问题
unity·光照贴图
曹牧2 小时前
C#:窗体构造函数无法引用窗体控件
开发语言·c#
iAkuya3 小时前
(leetcode)力扣100 54实现Trie树
算法·leetcode·c#
xb11323 小时前
C#使用Cancellation来取消异步任务
开发语言·c#
m0_748229993 小时前
C与C#:编程语言的核心差异解析
c语言·开发语言·c#
m0_748229993 小时前
Laravel7.x核心特性全解析
c语言·数据库·c#
阿蒙Amon4 小时前
C#每日面试题-Task和Thread的区别
java·面试·c#
ytttr8735 小时前
C#实现海康威视智能车牌识别
开发语言·c#
bubiyoushang8886 小时前
C#开发的TCP/UDP网络调试助手
tcp/ip·udp·c#