You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua脚本执行.timeset命令生成txt文件无写入内容问题排查求助

Lua计时器脚本问题排查与修复

存在的问题

  • 调用了Lua标准库不存在的string.insert方法,参数收集逻辑直接失效
  • 遍历参数时每次都用w覆盖模式写入文件,导致最终文件仅保留最后一个参数,后续读取4行参数的逻辑只会返回nil,触发运算报错
  • 从文件读取的字符串类型内容没有转换为数字,直接做算术运算会抛出类型错误
  • 逻辑顺序错误:不需要每遍历一个参数就执行一次读写、计算逻辑,应该先收集全4个参数,再批量写入、读取、换算

修复后完整代码

function readFile(file)
    local lines = io.lines(file)
    local result = {}
    
    for line in lines do 
        table.insert(result, line)
    end
    return result
end

function writeFile(file, text)
    local wrFile = io.open(file, "w")
    if not wrFile then
        print("文件打开失败:"..file)
        return
    end
    io.output(wrFile)
    io.write(text)
    io.close(wrFile)
end

command = "timeset"
help_message = "Set your Timer! Format: Days Hours Minutes Seconds"

function execute(arguments)
    -- 第一步:收集全部4个参数
    local args = {}
    for word in string.gmatch(arguments, "[^%s]+") do
        table.insert(args, word)
    end
    if #args ~= 4 then
        print(help_message)
        return
    end

    -- 第二步:将4个参数写入原始参数文件
    local rawContent = table.concat(args, "\n")
    writeFile("timerset_raw.txt", rawContent)

    -- 第三步:读取原始参数文件,转换为数字后计算总秒数
    local rawParams = readFile("timerset_raw.txt")
    local dayst = tonumber(rawParams[1])
    local hourst = tonumber(rawParams[2])
    local mint = tonumber(rawParams[3])
    local sect = tonumber(rawParams[4])

    if not (dayst and hourst and mint and sect) then
        print("所有参数必须为有效数字")
        return
    end

    local totalSec = dayst * 86400 + hourst * 3600 + mint * 60 + sect

    -- 第四步:将总秒数写入新文件
    writeFile("timerset.txt", totalSec)
end

内容的提问来源于stack exchange,提问作者SebyGHG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:36:00