Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 32 ยท Functions

Varargs and Closures

Write Lua functions that take any number of arguments with ..., use select and table.pack, and build counters and factories with closures and upvalues.

Two features turn Lua functions from simple helpers into a serious toolkit. The first is the vararg: a function that accepts any number of arguments. The second is the closure: a function that remembers variables from the place where it was created, even after that place has finished running.

Both build on what you saw in Functions, where functions were shown to be ordinary values. Lua is not installed on this site, so the Lua listings below are read-only and the runnable examples are JavaScript stand-ins that model the same behavior. Where closures in JavaScript and Lua behave the same, the stand-in shows it faithfully.

Variable arguments with ...

Three dots in a parameter list mean "and any number of further arguments". Inside the function, ... stands for that list of values:

LUA
local function count(...)
  print(select("#", ...), "arguments")
end

count()              --> 0 arguments
count("a", "b")      --> 2 arguments
count(nil, nil)      --> 2 arguments

You can put regular parameters before the dots: function log(level, ...). The ... must come last. It is not a table and not a single value, so you cannot write #.... You can pass it on to another function, or capture it in several ways.

The simplest capture is a local assignment, which takes as many values as it has names:

LUA
local function firstTwo(...)
  local a, b = ...
  return a, b
end

print(firstTwo(10, 20, 30))   --> 10   20

Another way is to wrap it in a table constructor, {...}, which gives you a list you can loop over with ipairs:

LUA
local function sum(...)
  local total = 0
  for _, value in ipairs({...}) do
    total = total + value
  end
  return total
end

print(sum(1, 2, 3, 4))   --> 10

select and nil arguments

{...} has a weakness: if any argument is nil, the list gets holes, and ipairs or # may stop early. The select function reads varargs without building a table:

  • select("#", ...) returns the number of arguments, counting nils.
  • select(n, ...) returns the arguments from position n onward.
  • A negative n counts from the end: select(-1, ...) is the last argument.
LUA
print(select("#", "a", nil, "c"))   --> 3
print(select(2, "a", "b", "c"))     --> b   c
print(select(-1, "a", "b", "c"))    --> c

To visit each argument including nils, loop with the count:

LUA
local function show(...)
  for i = 1, select("#", ...) do
    local value = select(i, ...)
    print(i, value)
  end
end

show("x", nil, "z")
-- 1   x
-- 2   nil
-- 3   z

table.pack and table.unpack

Lua 5.2 and later provide a pair of functions that convert between varargs and tables. table.pack(...) returns a table of all the arguments with an extra field n holding the true count, so nils do not lose information. table.unpack(t, i, j) does the reverse: it returns t[i] through t[j] as separate values (by default from 1 to #t):

LUA
local packed = table.pack("a", nil, "c")
print(packed.n)                    --> 3
print(packed[1], packed[2], packed[3])   --> a   nil   c

local list = {10, 20, 30}
print(table.unpack(list))          --> 10   20   30
print(table.unpack(list, 2, 3))    --> 20   30

Because unpack returns many values, it is the way to call a function with arguments stored in a list: math.max(table.unpack(list)). (Older Lua 5.1 and LuaJIT call it just unpack.)

Working with varargs

... Stands for all extra arguments.
select("#", ...) How many, nils included.
select(n, ...) Everything from position n.
table.pack A list plus the field n.
1 / 2

Try it: counting and packing arguments

The stand-in uses JavaScript rest parameters. JavaScript's arguments.length plays the role of select("#", ...), and an array with explicit undefined entries models a list containing nil.

JS Varargs stand-in (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Functions are first-class values

"First-class" means functions can be stored in variables and tables, passed as arguments and returned from other functions. You have seen the first two. The third one is where things get interesting:

LUA
local function multiplier(factor)
  return function(x)
    return x * factor
  end
end

local double = multiplier(2)
local triple = multiplier(3)

print(double(5))   --> 10
print(triple(5))   --> 15

multiplier has finished running by the time double(5) is called. Yet the returned function still knows factor. That is a closure.

Closures and upvalues

A function defined inside another function can use the outer function's local variables. Those variables are called upvalues of the inner function. Lua keeps them alive for as long as some function still refers to them, even though the code that created them has returned.

The classic example is a counter:

LUA
local function newCounter()
  local count = 0
  return function()
    count = count + 1
    return count
  end
end

local a = newCounter()
local b = newCounter()

print(a(), a(), a())   --> 1   2   3
print(b())             --> 1

Each call to newCounter creates a new count variable and a new function that owns it. a and b therefore count separately. And since count is a local that no other code can name, the counter is also private: the only way to change it is to call the function. Lua programmers use this to hide state without needing classes (Objects and Classes shows how).

Two closures can even share one upvalue:

LUA
local function newAccount(balance)
  local function deposit(n) balance = balance + n end
  local function current() return balance end
  return deposit, current
end

local deposit, current = newAccount(100)
deposit(50)
print(current())   --> 150

Here balance is a parameter, which is a local too, so both functions see the same variable.

Closures in loops

Each pass of a for loop creates a fresh loop variable. A closure created in the body captures that pass's variable, not a shared one:

LUA
local printers = {}
for i = 1, 3 do
  printers[i] = function() print(i) end
end

printers[1]()   --> 1
printers[2]()   --> 2
printers[3]()   --> 3

Compare this with a while loop that updates one variable declared outside: every closure would then see the same, final value. If you need separate copies there, declare a new local inside the body.

Try it: counters and factories

JavaScript closures work the same way, so this stand-in is a faithful picture. Notice that a and b have separate state, and that the three loop closures remember different values.

JS Closures stand-in (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does select("#", nil, nil) return?

    select with "#" counts all arguments, including nils, so the result is 2.
  2. 2. Why use table.pack(...) instead of {...}?

    A table built with {...} can have holes whose length is unreliable. table.pack adds n, the exact count.
  3. 3. What is an upvalue?

    An upvalue is an outer local captured by an inner function. Lua keeps it alive as long as the closure exists.
  4. 4. After local a, b = newCounter(), newCounter(), calling a() three times and then b() returns what for b()?

    Every call to newCounter creates a new count variable, so b starts from its own zero and returns 1.

Summary

  • ... collects extra arguments; it must be the last parameter.
  • select("#", ...) counts arguments (nils included) and select(n, ...) returns those from position n on, with negative n counting from the end.
  • table.pack(...) returns a list with the count in n; table.unpack(t) turns a list back into separate values.
  • A closure is a function plus the upvalues it captured from enclosing functions.
  • Each call to a factory creates fresh upvalues, so counters are independent and their state is private.
  • Each for iteration has its own loop variable, so closures created in the body keep different values.

Continue with Recursion and Tail Calls.