LUA / CHAPTER 04

Multiple results and exact argument packs

Intermediate

Preserve nil values and understand result adjustment.

By the end of this chapter

  • Trace where calls expand to multiple results
  • Use table.pack and its n field
  • Forward arguments with explicit unpack bounds

The idea

Lua functions can return several values, but expression position controls how many are retained. A function call at the end of an expression list can contribute all its results; a call in an earlier position is adjusted to one result. Parentheses around a call also force a single result. These rules matter when forwarding helper results or building table constructors.

Varargs represent an argument list that may include nil values. A plain sequence table cannot reliably encode trailing nil arguments through its length operator. In Lua 5.4, table.pack stores an explicit n count, and table.unpack with bounds one through n can reconstruct the original arity. Distinguish the number of arguments from the number of non-nil values when designing wrappers.

Lua example
local packed=table.pack(2,nil,7)
print(packed.n)
print(packed[2]==nil)
print(select("#",table.unpack(packed,1,packed.n)))
Result
3
true
3

The explicit count retains arity even though the middle position is nil. Bounded unpack forwards all three positions.

Try it yourself

Write a wrapper that forwards all results of another function, including trailing nil.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which field records the exact arity in a table.pack result?