当前位置: 首页 > article >正文

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

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

-- 定义日志文件路径和最大行数
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

http://www.kler.cn/a/427953.html

相关文章:

  • 【项目初始化】
  • 【微服务与分布式实践】探索 Eureka
  • 网站快速收录:利用新闻源的优势
  • Linux Samba 低版本漏洞(远程控制)复现与剖析
  • AboutDialog组件的功能和用法
  • 基于亿坊PHP框架构建物联网解决方案的优势分析!
  • gitee常见命令
  • 日本IT|AWS技术方向都需要做哪些工作呢?
  • 认证插件介绍
  • 【Pytorch】学习第一弹——张量数据类型、创建张量、索引与切片、维度变换、Broadcasting、合并与分割、数学运算
  • Django drf基于APIView 快速使用
  • 网络渗透实验四(渗透课)
  • 《Opencv》Canny边缘检测操作
  • 代码随想录-算法训练营day45(动态规划07:爬楼梯进阶本,零钱兑换,完全平方数)
  • 健康养生:身心和谐的生活艺术
  • 算法日记 43-44 day 图论(深搜,广搜)
  • 【ESP32】ESP-IDF开发 | DAC数模转换器+余弦波输出例程
  • Flink:入门介绍
  • deepsort复现报错TypeError: tuple indices must be integers or slices, not tuple 解决
  • CSES-1141 Playlist
  • RoformerBERT介绍
  • 架构10-可观测性
  • Unity 设计模式-观察者模式(Observer Pattern)详解
  • 3D 生成重建019-LERF用文本在Nerf中开启上帝之眼
  • 算法训练-位运算
  • Next.js系统性教学:服务器操作与数据变更