Lua Project: Config Interpreter
A config interpreter is a small program that reads configuration data and turns it into a summary. It fills gaps, checks values, and prints the result in a fixed order.
A missing setting takes its default
The interpreter checks for a missing field. When it finds one, it copies the default in.
local config = { title = "Shop" }
local defaults = { title = "Untitled", theme = "light" }
if config.theme == nil then config.theme = defaults.theme end
print(config.theme)An out-of-range value is rejected
The port must sit inside its allowed range. A value above the top of the range fails the check.
local config = { port = 70000 }
if config.port >= 1 and config.port <= 65535 then print("port ok") else print("port rejected") endThe summary follows a fixed order
A list of keys sets the print order. The summary then reads the same way every time.
local config = { title = "Shop", theme = "light" }
local order = { "title", "theme" }
for _, key in ipairs(order) do print(key .. ": " .. config[key]) endExample
local config = { name = "Corner Shop", port = 9000 }
local defaults = { port = 8000, theme = "light", workers = 2 }
local keys = { "port", "theme", "workers" }
for _, key in ipairs(keys) do
if config[key] == nil then config[key] = defaults[key] end
end
local valid = config.port >= 1 and config.port <= 65535 and config.workers >= 1 and config.workers <= 8
if valid then
local order = { "name", "port", "theme", "workers" }
for _, key in ipairs(order) do print(key .. ": " .. config[key]) end
else
print("config rejected")
endKey points
- Data first: the configuration is a plain table of named settings.
- Defaults: a missing setting is filled from a defaults table.
- Validation: a setting outside its allowed range is rejected.
- Summary: the interpreter prints a readable summary, not the raw table.
- Order: settings are printed in a fixed list order, so output order is stable.
In this example, the configuration gives a name and a port, while the theme and worker count are missing. The interpreter fills both from the defaults table. The port and worker count pass their range checks, so the summary prints in fixed order.
Note
configuration data is data, not program code, so it cannot call functions.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A configuration leaves the theme out, and the defaults table sets it to light. What does the interpreter print for the theme?