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

如何让Lua自定义时间函数newtime实现类似os.date的格式化输出?

实现类似os.date格式化输出的Lua函数newtime

我编写了如下Lua函数newtime,它获取当前时间并计算后返回包含ye、mo、da字段的表:

function newtime()
    t1 = os.date("*t")
    -- 这里是计算chha_ye, chha_mo, chha_da的逻辑
    t={} 
    t["ye"] = chha_ye
    t["mo"] = chha_mo
    t["da"] = chha_da
    return t
end

目前可以通过newtime().ye的方式访问对应字段,现在需要让该函数实现类似os.date的格式化输出功能:比如当chha_ye=4、chha_mo=9时,调用newtime("%ye")返回4,调用newtime("%ye - %mo")返回"4 - 9",就像os.date的使用方式:

os.date("%Y")
-- 输出 22
os.date("%Y - %m")
-- 输出 "22 - 10"

请问该如何实现这一功能?


实现方案

核心思路是让newtime支持可选的格式化参数:无参时返回字段表,有参时解析占位符并替换为对应值。修改后的代码如下:

function newtime(format)
    t1 = os.date("*t")
    -- 保留你原本计算chha_ye, chha_mo, chha_da的逻辑
    local chha_ye = 4 -- 示例值,替换为你的实际计算结果
    local chha_mo = 9 -- 示例值,替换为你的实际计算结果
    local chha_da = 15 -- 示例值,替换为你的实际计算结果

    local time_table = {
        ye = chha_ye,
        mo = chha_mo,
        da = chha_da
    }

    -- 无格式化参数时,返回原字段表
    if not format then
        return time_table
    end

    -- 匹配并替换格式化占位符
    local result = format:gsub("%%(%w+)", function(match)
        return time_table[match] or "" -- 未知占位符替换为空
    end)

    -- 模仿os.date,纯数字结果返回数值类型,否则返回字符串
    local num_result = tonumber(result)
    return num_result or result
end

关键细节说明

  • 参数兼容:新增format可选参数,不影响原有的newtime().ye调用方式;
  • 占位符解析:用string.gsub的模式"%%(%w+)"匹配%开头的占位符,捕获字段名后从time_table取值替换;
  • 类型处理:替换后判断结果是否为纯数字,是则返回数值,否则返回字符串,和os.date行为一致。

测试验证

print(newtime().ye)          -- 输出 4
print(newtime("%ye"))        -- 输出 4
print(newtime("%ye - %mo"))  -- 输出 "4 - 9"
print(newtime("%da/%mo/%ye"))-- 输出 "15/9/4"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:20:28