如何将txt指令编码列表转换为可遍历Lua表并实现迭代执行流程
text.txt编码列表的Lua解析与顺序执行实现
一、解析为可遍历表结构
直接按行读取text.txt,过滤空行后按两行一组拆分,存入数组型table,代码如下:
-- 解析text.txt为指令列表 local function parse_command_list(file_path) local cmd_list = {} -- 以只读模式打开文件 local file = io.open(file_path, "r") if not file then error("无法打开文件: "..file_path) end -- 按行读取,跳过空行 local lines = {} for line in file:lines() do line = line:gsub("%s+$", "") -- 去除行尾空白 if line ~= "" then table.insert(lines, line) end end file:close() -- 每两行分为一组指令 for i = 1, #lines, 2 do local cmd_name = lines[i] local cmd_code = lines[i+1] -- 校验配对是否完整 if not cmd_name or not cmd_code then error("第"..i.."行附近指令配对不完整,请检查text.txt格式") end table.insert(cmd_list, { name = cmd_name, code = cmd_code }) end return cmd_list end
返回的cmd_list为纯数组结构,可直接通过for i, cmd in ipairs(cmd_list) do ... end遍历,满足逐行迭代需求。
二、实现带日志标记的顺序执行流程
采用双文件设计:send_log.txt存储所有指令的发送状态,可选搭配progress.txt记录当前执行进度,支持中断后从上次位置继续。
完整逻辑代码:
-- 替换为你实际的编码发送接口,参数为解析后的十六进制编码串 local function send_hex_code(code_str) -- 这里写实际的发送逻辑,比如串口发送、TCP发送等 print("正在发送编码: "..code_str) -- 测试用打印 end -- 替换为你实际的平台延时接口,单位为秒 local function delay(seconds) -- 纯Lua环境:Windows用os.execute("ping -n 1 127.0.0.1 >nul"),Linux用os.execute("sleep "..seconds) -- 带socket的环境直接用 socket.sleep(seconds) print("等待"..seconds.."秒") -- 测试用打印 end -- 初始化日志文件 local function init_log(cmd_list) local log_file = io.open("send_log.txt", "w") for i, cmd in ipairs(cmd_list) do log_file:write(string.format("[待发送] %s\n", cmd.name)) end log_file:close() end -- 主执行流程 local function run_commands() -- 1. 解析指令列表 local cmd_list = parse_command_list("text.txt") -- 2. 初始化日志(仅首次运行时执行,若要支持断点续传可注释掉) init_log(cmd_list) -- 3. 逐条执行 for idx, cmd in ipairs(cmd_list) do -- 3.1 记录当前待执行指令 print("当前待执行指令: "..cmd.name) -- 3.2 发送对应编码 send_hex_code(cmd.code) -- 3.3 更新日志:标记当前指令为已发送 local log_file = io.open("send_log.txt", "r") local log_lines = {} for line in log_file:lines() do table.insert(log_lines, line) end log_file:close() -- 替换对应行的状态 log_lines[idx] = log_lines[idx]:gsub("%[待发送%]", "[已发送]") -- 重写日志文件 log_file = io.open("send_log.txt", "w") for _, line in ipairs(log_lines) do log_file:write(line.."\n") end log_file:close() -- 3.4 短延时 delay(0.2) -- 可修改为需要的延时时长,单位秒 end end -- 启动执行 run_commands()
三、可选优化
- 断点续传:新增
progress.txt,每执行完一条指令就把当前数组索引写入该文件,下次启动时直接读取索引跳过已执行的条目,避免重复发送 - 编码校验:如果十六进制编码有固定格式,可在解析阶段增加格式校验,提前拦截文件生成错误
- 日志拆分:如果指令数量极多,可将待执行指令名单独写入
pending.txt,已发送标记写入sent.txt,避免单次读写整个日志文件
内容的提问来源于stack exchange,提问作者nodecentral
相关产品推荐
相关产品推荐

