Menu
CoddyTech

null and Missing Fields

Lesson 7 of 48 in Coddy's Lua for GDScript Developers course.

GDScript uses null for the absence of an object or a value in a Variant. Lua uses nil. A GDScript dictionary can store null under a key and still report that key through has(). Lua tables cannot retain a key whose value is nil: assigning it removes the entry. Reading an absent Lua field also returns nil. A stored false is different because the key remains present. Check value == nil when you mean missing, and use type(value) when distinguishing boolean and string values. Testing only the value's truthiness merges missing data with a deliberately stored false setting.

GDScript 4

extends SceneTree

func _init():
	var settings = {"enabled": false}
	settings["enabled"] = null
	print("present" if settings.has("enabled") else "absent")
	quit()

Lua 5.1

local settings = {enabled = false}
settings.enabled = nil
if settings.enabled == nil then
  print("absent")
else
  print("present")
end

Porting trap

Porting settings["enabled"] = null to settings.enabled = nil changes key presence. Lua removes the field rather than retaining a null-valued entry.

challenge icon

Challenge

Easy

Input is missing, false, or another text value. Treat missing as an absent field, false as a stored boolean, and other text as a stored string. Return absent, boolean, or string.

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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for GDScript Developers

Practice on your own: Online Lua compiler