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
相关推荐
IMPYLH18 小时前
Lua 的 xpcall 函数
开发语言·笔记·后端·游戏引擎·lua
一帘忧梦1 天前
linux 系统rcs脚本启动
linux·运维·lua
IMPYLH2 天前
Lua 的 warn 函数
java·开发语言·笔记·junit·lua
石头wang2 天前
postman如何设置鉴权authorization header(怎么只设置一次,统一管理,不要每个request重复设置)
测试工具·lua·postman
qq_348231853 天前
Redis 事务(MULTI/EXEC)与 Lua 脚本的核心区别
数据库·redis·lua
没有腰的嘟嘟嘟3 天前
从 0 到 1:我如何用 Spring Boot 3 + Redis 打造一个生产级通用幂等与防重中间件(含图解 + 代码 + 案例)
spring boot·redis·中间件·lua
小雨下雨的雨3 天前
第5篇:Redis事务与Lua脚本
redis·junit·lua
BuHuaX4 天前
Lua入门
开发语言·unity·junit·c#·游戏引擎·lua
根哥的博客5 天前
编译nginx-1.28.0支持lua语法
nginx·lua·openresty·nosql注入漏洞
8Qi85 天前
Redis之Lua脚本与分布式锁改造
java·redis·分布式·lua