Menu
CoddyTech

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

Practice on your own: Online Lua compiler