Lua Config Files with Environments
A config file with an environment is a data file that runs under a table that captures its settings. The file holds assignments only, and each assignment lands in the capturing table.
One setting lands in the table
The file sets one value. After it runs, the table holds that value.
local file = io.open('settings.lua', 'w')
file:write('theme = "dark"\n')
file:close()
local settings = {}
local f = loadfile('settings.lua', 't', settings)
f()
print(settings.theme)Several settings land in the same table
The file sets two numbers. Both appear in the same table after it runs.
local file = io.open('settings.lua', 'w')
file:write('width = 800\nheight = 600\n')
file:close()
local settings = {}
local f = loadfile('settings.lua', 't', settings)
f()
print(settings.width)
print(settings.height)A setting does not become a global
The table holds the title, but the global name reads as nil. The setting did not leak out.
local file = io.open('settings.lua', 'w')
file:write('title = "Notes"\n')
file:close()
local settings = {}
local f = loadfile('settings.lua', 't', settings)
f()
print(settings.title)
print(title)Example
local file = io.open('settings.lua', 'w')
file:write('title = "Reader"\nwidth = 1024\ndark = true\n')
file:close()
local settings = {}
local f = loadfile('settings.lua', 't', settings)
f()
print(settings.title)
print(settings.width)
print(settings.dark)Key points
- loadfile: a function that turns a file of code into a function, like load for a file.
- Argument order: path, mode, then environment table.
- Capturing table: the empty table passed as the environment collects the settings.
- Assignment capture: each assignment in the file writes into the capturing table.
- No global leak: settings in the file do not become globals of the main program.
In this example, the program first writes a file with three assignments. It then loads that file under the empty settings table, runs it, and prints the three captured values in order.
Note
these lessons write the file first, because the case folder starts empty.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A config file sets width = 800 and runs under settings. What does print(settings.width) show?