Menu
CoddyTech

Multiple Results and Varargs

Lesson 19 of 48 in Coddy's Lua for GDScript Developers course.

GDScript returns a single value. A helper that reports both minimum and maximum can return an array or dictionary, and the caller then extracts its elements. Lua can return several values directly with return minimum, maximum, and a multiple assignment receives them separately. A missing result fills the corresponding local with nil; excess results are discarded. Lua varargs use ... in the parameter list and body. For a numeric bounds helper, collect those arguments with {...}, and use select("#", ...) to count arguments when needed. Multiple return values are not an automatically constructed table. Use explicit braces when a stored collection is required. Lua 5.1 expands a dense sequence with global unpack(values). For arguments containing nil, retain an explicit count and pass it as the final index to unpack; table length cannot reliably count holes.

GDScript 4

extends SceneTree

func bounds(values: Array) -> Array:
	return [values.min(), values.max()]

func _init():
	var result = bounds([7, 2, 9])
	print(str(result[0]) + ":" + str(result[1]))
	quit()

Lua 5.1

local function bounds(...)
  local values = {...}
  local low, high = values[1], values[1]
  for index = 2, select("#", ...) do
    low = math.min(low, values[index])
    high = math.max(high, values[index])
  end
  return low, high
end
local low, high, extra = bounds(7, 2, 9)
print(low .. ":" .. high .. ":" .. tostring(extra))

Porting trap

local result = bounds(...) keeps only the first return value. It does not create the array that a GDScript caller may expect.

challenge icon

Challenge

Easy

Input is a sequence of integer lines, possibly empty. Define bounds(...) using varargs. Return minimum and maximum separated by a colon, or empty when no values are supplied.

Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.

Try it yourself

local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for GDScript Developers

Practice on your own: Online Lua compiler