False Values and Defaults
Lesson 5 of 29 in Coddy's Lua for Luau Developers course.
Truth rules already match: only false and nil are falsey; zero and empty strings are truthy. The porting hazard is Luau conditional expressions. A Luau if ... then ... else ... expression can select a false value. Lua 5.1 has only the statement form. The often-used condition and value or fallback idiom loses a selected false or nil value because the second operator chooses the fallback. Use a local result and explicit branches when either result may be falsey. Likewise, a missing optional field needs a nil check if an explicitly supplied false must survive.
Luau
local enabled: boolean? = false
local chosen = if enabled == nil then true else enabled
print(chosen)Lua 5.1
local enabled = false
local chosen
if enabled == nil then chosen = true else chosen = enabled end
print(chosen)Porting trap
An optional Luau boolean annotation describes allowed values; it does not choose a default. Preserve that defaulting rule in the Lua implementation.
Challenge
EasyInput is nil, false, 0, or empty. Decode it to nil, false, zero, or an empty string. Return truthy or falsy using Lua truth rules.
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 Luau Developers
1Syntax and Runtime
Run Lua ModulesInterpolation to TextFloor Division and NumbersBytes and UTF-8 LibrariesFalse Values and DefaultsConditional ExpressionsPractice on your own: Online Lua compiler