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 天前
怎么使用postman批量的给api做测试
测试工具·lua·postman
最贪吃的虎3 天前
Redis其实并不是线程安全的
java·开发语言·数据库·redis·后端·缓存·lua
_200_4 天前
Lua 流程控制
开发语言·junit·lua
Kang.Charles4 天前
Lua UI系统框架逻辑详解
ui·lua
oMcLin4 天前
如何在 Rocky Linux 8.6 上配置并调优 Nginx 与 Lua 脚本,提升 API 网关的性能与并发处理能力
linux·nginx·lua
姓蔡小朋友5 天前
LUA脚本
开发语言·junit·lua
金融新世界5 天前
推动产业升级:倒逼转型创新与重构产业链格局
lua
oMcLin5 天前
如何在 Debian 11 上配置并优化 Nginx 与 Lua 脚本,提升高并发网站的动态请求处理能力?
nginx·debian·lua
源代码•宸6 天前
goframe框架签到系统项目开发(补签逻辑实现、编写Lua脚本实现断签提醒功能、简历示例)
数据库·后端·中间件·go·lua·跨域·refreshtoken
每天回答3个问题6 天前
Lua 函数教程
开发语言·ue5·ue4·lua