Object Patterns with Tables
Default Field
Choose a default when an object-style field is blank.
default field
Object-style records often need defaults for missing or blank fields.
Default Field
default_field.lua
Replay: real traced execution (multi-file project)
local explicit = ""
local fallback = ({theme = "gray"}).theme
local theme = explicit
if theme == nil or theme == "" then
theme = fallback
end
print("theme=" .. theme)
local explicit = "blue"
local fallback = ({theme = "gray"}).theme
local theme = explicit
if theme == nil or theme == "" then
theme = fallback
end
print("theme=" .. theme)
local explicit = nil
local fallback = ({theme = "gray"}).theme
local theme = explicit
if theme == nil or theme == "" then
theme = fallback
end
print("theme=" .. theme)
explicit ← (empty), fallback ← gray, theme ← (empty)
1local explicit→ (empty) = "" --@explicit="blue", nil2local fallback→ gray = ({theme = "gray"}).themegray3local theme→ (empty) = explicit(empty)4if theme == nil or theme == "" thentheme ← gray
3local theme = explicit4if theme(empty) == nil or theme == "" then5 theme→ gray = fallbackgray6endprint("theme=" .. theme)
6end7print("theme=" .. themegray)outputtheme=gray
explicit ← blue, fallback ← gray, theme ← blue
1local explicit→ blue = "blue"2local fallback→ gray = ({theme = "gray"}).themegray3local theme→ blue = explicitblue4if theme == nil or theme == "" then5 theme = fallback6end7print("theme=" .. themeblue)outputtheme=blue
explicit ← nil, fallback ← gray, theme ← nil
1local explicit→ nil = nil2local fallback→ gray = ({theme = "gray"}).themegray3local theme→ nil = explicitnil4if theme == nil or theme == "" thentheme ← gray
3local theme = explicit4if themenil == nil or theme == "" then5 theme→ gray = fallbackgray6endprint("theme=" .. theme)
6end7print("theme=" .. themegray)outputtheme=gray