Multiple Returns and Default Arguments
Prerequisites: Functions
Returning several values
local function minMax(list)
local lo, hi = list[1], list[1]
for _, v in ipairs(list) do
if v < lo then lo = v end
if v > hi then hi = v end
end
return lo, hi
end
local low, high = minMax({4, 9, 1, 7})
print(low, high)
print(minMax({3, 8}))
print((minMax({3, 8})))
print(minMax({3, 8}), "end")
1 9
3 8
3
3 end
return a, breturns two values; assign them to two variables.- Extra parentheses keep only the first value.
- A call keeps all its values only when it's last in a list —
minMax(...), "end"passes just the first result.
Returning nil, "error message" on failure is a common Lua convention
(io.open does it).
Default arguments
Lua has no default-argument syntax. Use or:
local function connect(host, port, secure)
port = port or 443
if secure == nil then secure = true end
local scheme = secure and "https" or "http"
return scheme .. "://" .. host .. ":" .. port
end
print(connect("example.com"))
print(connect("localhost", 8080, false))
https://example.com:443
http://localhost:8080
port = port or 443 works for numbers and strings, but for booleans
x or true would turn an explicit false into true — compare with
nil instead.
Named arguments with a table
For many optional settings, pass one table:
local function createWindow(opts)
local title = opts.title or "Untitled"
local width = opts.width or 800
local height = opts.height or 600
return string.format("%s (%dx%d)", title, width, height)
end
print(createWindow{title = "Editor", width = 1024})
print(createWindow{})
Editor (1024x600)
Untitled (800x600)
When the only argument is a table or string literal, the parentheses can
be dropped: createWindow{...}, require "json".