lua 一个简单的table变量序列化和日志写入函数

lua将table类型变量转换成string类型函数serialize和一个简单的日志写入函数write_log

lua 复制代码
-- 定义日志文件路径和最大行数
local log_file = "/tmp/lua_log"
local max_lines = 20000  -- 设置最大行数

-- 定义一个简单的table序列化函数
function serialize(tbl)
    local result = {}
    for k, v in pairs(tbl) do
        -- 处理键
        if type(k) == "string" and string.match(k, "^%a[%w_]*$") then
            table.insert(result, k .. " = ")
        else
            table.insert(result, "[" .. tostring(k) .. "] = ")
        end

        -- 处理值
        if type(v) == "table" then
            table.insert(result, "{" .. serialize(v) .. "},")
        elseif type(v) == "string" then
            table.insert(result, string.format("%q", v) .. ",")
        else
            table.insert(result, tostring(v) .. ",")
        end
    end
    return table.concat(result)
end

-- 检查并可能清空日志文件
local function check_and_clear_log()
    local f, err = io.open(log_file, "r")
    if not f then
        dbg("无法打开日志文件: " .. err)
        return
    end
    local lines = {}
    for line in f:lines() do
        table.insert(lines, line)
    end
    f:close()

    if #lines >= max_lines then
        -- 清空文件
        f, err = io.open(log_file, "w")
        if not f then
            dbg("无法打开日志文件以清空: " .. err)
            return
        end
        f:close()
    end
end

-- 写入日志
function write_log(message)
    check_and_clear_log()  -- 在每次写入前检查是否需要清空文件
    message = os.date("%Y-%m-%d %H:%M:%S - ") .. os.time().." - "..message

    local f, err = io.open(log_file, "a+")
    if not f then
        dbg("无法打开日志文件进行追加: " .. err)
        return
    end
    f:write(message .. "\n")  -- 写入消息并换行
    f:close()
end
相关推荐
二喵❥(^_-)1 天前
接口测试流程的三个核心环节
开发语言·lua
小师兄吃牛肉7 天前
C++ 与 Lua 的协程交互:从原理到实战
c++·lua·交互
喜欢的名字被抢了7 天前
09-Redis 进阶原理篇:单线程、多线程、过期、LRU-LFU、Fork 与 Lua
数据库·redis·lua
白山编程大哥8 天前
Lua 中使用 C 语言的用户自定义类型——userdata
c语言·junit·lua
大侠归来10 天前
C++ 与 Lua 的协程交互:从原理到实战
c++·lua·交互
疯狂成瘾者11 天前
海康 Artemis 接口对接
开发语言·lua
一线灵11 天前
跨平台游戏引擎 Axmol-2.11.5 发布
游戏引擎·lua
liulilittle20 天前
麻将结算全链路语义(SETTLE_SEMANTICS)
ai·自动化·llm·mock·lua·测试
liulilittle20 天前
麻将服务器崩溃补偿与异常处理语义(CRASH_SEMANTICS)
ai·自动化·llm·mock·lua·测试·tools
liulilittle20 天前
麻将 UI 层可观察行为(UI_BEHAVIOR)
ai·自动化·llm·mock·lua·测试·tools