Return multiple values with strict type-checking

I would like to learn how to return multiple values from a function with strict type checking.

To return one value from a function, I would write type notation in the following way:

local function foo(): boolean
    -- function code
    return true
end

But what if I wanted to return two values from a function (e.g. a tuple)? How would I add type notation for this?

local function foo() -- ... don't know what to add here
    return 1, 2, 3, 4
end

I think

function foo(): (number,number,...)

would work

1 Like

If you want to return an unknown amount of the same type, you would do this:

local function foo(): ...number
	return 1, 2, 3, 4
end

If you are returning different types:

local function foo(): (boolean, string, number)
	return true, '', 123
end

And an unknown number of types where the first few types are known:

local function foo(): (string, ...number)
	return '', 1, 2, 3
end

If you want to do function overload, you need to define the function’s type into an actual type, and then intersect the variations. Note that typechecking doesn’t like the definition of the overloaded function itself, so you might get warnings that need to be manually silenced.

type foo = ((string) -> number) & ((number) -> string)

local function foo(input)
	if type(input) == 'string' then
		return 1::any
	end
	if type(input) == 'number' then
		return ''::any
	end
	return
end
local foo: foo = foo::any

local a: number = foo('')
local b: string = foo(1)

And finally, you use generics for generic function return types.

local function twice<T>(input: T): (...T)
	return input, input
end

local a, b: number = twice(1)
local c, d: boolean = twice(true)

Everything should be covered in the Luau docs:

7 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.