Defaults and Missing Values
Lesson 18 of 48 in Coddy's Lua for GDScript Developers course.
GDScript can declare a default directly in a parameter list, such as func repeat_name(name, count = 2). Lua 5.1 does not support that syntax. Missing arguments arrive as nil, so initialize a default inside the function. Use if count == nil then count = 2 end when absence is the only reason to substitute a value. An explicit zero must remain zero when it means no repetitions. Lua's count or 2 preserves zero because zero is true in Lua, but it also replaces false. The explicit nil check documents the intended contract and works for optional boolean settings too.
GDScript 4
extends SceneTree
func repeat_name(name: String, count: int = 2) -> String:
var copies = PackedStringArray()
for index in range(count):
copies.append(name)
return ",".join(copies) if count > 0 else "none"
func _init():
print(repeat_name("Ada"))
print(repeat_name("Ada", 0))
quit()Lua 5.1
local function repeat_name(name, count)
if count == nil then count = 2 end
local copies = {}
for index = 1, count do copies[index] = name end
if count == 0 then return "none" end
return table.concat(copies, ",")
end
print(repeat_name("Ada"))
print(repeat_name("Ada", 0))Porting trap
Do not use a positive-number test to select a default. That would replace an explicitly supplied 0, changing a valid request for no repetitions.
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 GDScript Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Missing ValuesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission RulesPractice on your own: Online Lua compiler