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

FormatSeconds(123456)

我该使用什么来仅获取一个例如 hours,或两个 minutesseconds

原文链接 https://stackoverflow.com/questions/69306331

点赞
stackoverflow用户10915018
stackoverflow用户10915018

你可以简单的返回一个数组(或者在 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"])
2021-09-23 20:26:08
stackoverflow用户16835308
stackoverflow用户16835308

你可以通过这种方式来获取函数的返回值而不会改变它的返回类型:

local weeks, _, _, _, _ = FormatSeconds(123456) -- 仅选择周
print(weeks)

要选择多个返回值:

local _, _, _, minutes, seconds = FormatSeconds(123456)
io.write(minutes, " 分钟 ", seconds, " 秒")
2021-09-23 21:04:23