Menu
CoddyTech

Multiple Results and Varargs

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

PHP returns a single value, often an array unpacked with destructuring. Lua can return several results without allocating a table. Assignment receives those results from a function call and fills missing slots with nil. Parentheses around a call reduce it to one result; so does placing it before another expression in an expression list. Lua varargs use .... In Lua 5.1, preserve a vararg count with select("#", ...) and use global unpack when expanding a stored sequence.

PHP

<?php
function pair(): array { return [2, 5]; }
[$a, $b] = pair();
echo $a + $b, "\n";

Lua

local function pair() return 2, 5 end
local a, b = pair()
print(a + b)

Porting trap

PHP spread syntax and Lua multiple results are different mechanisms. Lua 5.1 has no table.pack or table.unpack. A table containing trailing nil values needs a separate count because its length cannot reliably describe those arguments.

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 PHP Developers

Practice on your own: Online Lua compiler