欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > lua 一个简单的table变量序列化和日志写入函数

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

2025/2/24 19:28:15 来源:https://blog.csdn.net/toyijiu/article/details/144264850  浏览:    关键词: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_]*$") 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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词