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_]*$") thentable.insert(result, k .. " = ")elsetable.insert(result, "[" .. tostring(k) .. "] = ")end-- 处理值if type(v) == "table" thentable.insert(result, "{" .. serialize(v) .. "},")elseif type(v) == "string" thentable.insert(result, string.format("%q", v) .. ",")elsetable.insert(result, tostring(v) .. ",")endendreturn table.concat(result)
end-- 检查并可能清空日志文件
local function check_and_clear_log()local f, err = io.open(log_file, "r")if not f thendbg("无法打开日志文件: " .. err)returnendlocal lines = {}for line in f:lines() dotable.insert(lines, line)endf:close()if #lines >= max_lines then-- 清空文件f, err = io.open(log_file, "w")if not f thendbg("无法打开日志文件以清空: " .. err)returnendf:close()end
end-- 写入日志
function write_log(message)check_and_clear_log() -- 在每次写入前检查是否需要清空文件message = os.date("%Y-%m-%d %H:%M:%S - ") .. os.time().." - "..messagelocal f, err = io.open(log_file, "a+")if not f thendbg("无法打开日志文件进行追加: " .. err)returnendf:write(message .. "\n") -- 写入消息并换行f:close()
end