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,或两个minutes&seconds

您可以这样做,而无需改变函数的返回类型:

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

选择多个结果:

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

你可以简单地返回一个数组(或者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"])

相关内容

  • 没有找到相关文章

最新更新