Defaults and Options Tables
Lesson 18 of 48 in Coddy's Lua for Go Developers course.
Go has no ordinary default or named call arguments; configuration structs commonly carry optional settings. Lua often uses an options table and fills missing fields inside the function. A nil check preserves an explicit false value, while an or-true fallback would replace it. Decide whether the table itself is required and distinguish absence from a zero-valued setting.
Go
package main
import ("fmt")
type Options struct {Enabled bool}
func label(options Options) bool {return options.Enabled}
func main(){
fmt.Println(label(Options{}))
}
Lua
local function repetitions(options)
local n = options.repetitions
if n == nil then n = 2 end
return n
end
print(repetitions({}) .. ":" .. repetitions({repetitions = 0}))Porting trap
Fill only missing Lua option fields when false or zero is valid input.
Challenge
EasyFirst input line is a name. Optional second line is an integer repetitions value; default to 2 when absent. Zero means no repetitions. Return the name repeated that many times separated by commas, or none for zero.
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 Go 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