Lua - 我可以从 returns 多个结果的函数中选择我想要的特定结果吗

Lua - Can I pick the specific result(s) I want from a function that returns multiple results

有没有办法从 returns 多个结果的函数中选择我想要的结果。例如

local function FormatSeconds(secondsArg)

    local weeks = math.floor(secondsArg / 604800)
    local remainder = secondsArg % 604800
    local days = math.floor(remainder / 86400)
    local remainder = remainder % 86400
    local hours = math.floor(remainder / 3600)
    local remainder = remainder % 3600
    local minutes = math.floor(remainder / 60)
    local seconds = remainder % 60
    
    return weeks, days, hours, minutes, seconds
    
end

FormatSeconds(123456)

如果只抓取一个 hours 或两个 minutes & seconds

我会用什么

你可以简单地 return 一个数组(或者我认为 table in lua)然后索引你想要的结果

local function FormatSeconds(secondsArg)

    local weeks = math.floor(secondsArg / 604800)
    local remainder = secondsArg % 604800
    local days = math.floor(remainder / 86400)
    local remainder = remainder % 86400
    local hours = math.floor(remainder / 3600)
    local remainder = remainder % 3600
    local minutes = math.floor(remainder / 60)
    local seconds = remainder % 60

    return {weeks, days, hours, minutes, seconds}

end
-- weeks = 1, days = 2, hours = 3, minutes = 4, seconds = 5

print(FormatSeconds(123456)[3])

您也可以这样使用键值对和索引

return {["weeks"] = weeks, ["days"] = days, ["hours"] = hours, ["minutes"] = minutes, ["seconds"] = seconds}

然后这样打印

print(FormatSeconds(123456)["hours"])

或更简单的解决方案

local function FormatSeconds(secondsArg)

    arr = {}

    arr["weeks"] = math.floor(secondsArg / 604800)
    local remainder = secondsArg % 604800
    arr["days"] = math.floor(remainder / 86400)
    local remainder = remainder % 86400
    arr["hours"] = math.floor(remainder / 3600)
    local remainder = remainder % 3600
    arr["minutes"] = math.floor(remainder / 60)
    arr["seconds"] = remainder % 60
    
    return arr
    
end

print(FormatSeconds(123456)["hours"])

您可以这样做而不改变函数的 return 类型:

local weeks, _, _, _, _ = FormatSeconds(123456) -- Pick only weeks
print(weeks)

要选择多个结果:

local _, _, _, minutes, seconds = FormatSeconds(123456)
io.write(minutes, " minutes ", seconds, " seconds")