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 脚本是什么
开发语言·lua
LcGero1 天前
Lua 协程(Coroutine):游戏里的“伪多线程”利器
游戏·lua·游戏开发·协程
星夜泊客1 天前
《Lua 模块化核心:require 的地址传递与缓存机制》
缓存·lua
ling__i2 天前
接口测试常见问题
开发语言·lua
LcGero2 天前
Lua 进阶:元表(Metatable)如何实现“类系统”?
lua·元表
yyk的萌2 天前
AI 应用开发工程师基础学习计划
开发语言·python·学习·ai·lua
LcGero2 天前
Lua 的灵魂:Table 如何撑起整个游戏系统?
游戏·lua
lifewange4 天前
Postman如何实现接口自动化
自动化·lua·postman
上海合宙LuatOS4 天前
LuatOS扩展库API——【 excloud】AirCloud云平台控制
物联网·lua·luatos·合宙aircloud平台
he___H5 天前
Nginx+lua+openresty
nginx·lua·openresty