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

Is there a way to choose the result(s) I want from a function that returns multiple results . E.g.

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)

What would I use to only grab just one e.g hours, or two minutes & seconds

lua


Solution 1:[1]

You can do it this way without altering the return type of the function:

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

To pick more than one result:

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

Solution 2:[2]

You could simply return an array (or I think table in lua) and then index which result you want

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])

You could also use key value pairs and index that way

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

Then print this way

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

Or one more simpler solution

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"])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2