Multiple Results and Varargs
Lesson 19 of 48 in Coddy's Lua for C Developers course.
A C function can return a structure or write through output pointers to provide several results. Lua returns separate values directly, and a multi-variable assignment captures them in order. Unfilled destinations receive nil. A function accepting ... can inspect variable arguments; select("#", ...) counts them, including nil arguments. To retain both values and count, use {n = select("#", ...), ...}. Lua 5.1 expands that representation with global unpack(values, 1, values.n). Dense numeric sequences can simply use unpack(values). There is no need for C-style output addresses in the Lua call.
C
#include <stdio.h>
struct Pair { int first; int second; };
static struct Pair pair(void) {
struct Pair result = {2, 5};
return result;
}
int main(void) {
struct Pair values = pair();
printf("%d\n", values.first + values.second);
return 0;
}Lua
local function pair()
return 2, 5
end
local a, b = pair()
print(a + b)Porting trap
Only the final call in an expression list can expand. Parentheses force one result: local a, b = (pair()) leaves b nil. Lua 5.1 lacks table.pack and table.unpack.
Challenge
EasyInput 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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for C Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte PositionsRecap: Format a Receipt4Functions and Closures
Functions and ArgumentsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Absence and Table FieldsTruth and Default ValuesBranches and BoundsValues and Table IdentityRecap: Admission RulesPractice on your own: Online Lua compiler