Lua Loading Chunks
Chunk loading turns a string of Lua code into a function you can call later. Loading only compiles the code, and calling the result runs it.
A loaded chunk is a function
load returns a function. Calling it runs the code.
local f = load("return 7 * 6")
print(type(f))
print(f())Check a failed load before calling it
A bad chunk gives nil plus a message. Test the first return value before you call it.
local f, err = load("return 1 +")
print(f == nil)
print(err ~= nil)A mode can refuse a binary chunk
Mode t allows text chunks only. A binary chunk loaded with mode t fails.
local bin = string.dump(function() return 1 end)
local f, err = load(bin, nil, "t")
print(f == nil)
print(err ~= nil)loadfile loads a chunk from a file
The program writes its own file first. loadfile then turns that file into a function.
local file = io.open("chunk.lua", "w")
file:write("return 10 + 5")
file:close()
local f = loadfile("chunk.lua")
print(type(f))
print(f())Example
local env = {answer = 21}
local f = load("return answer * 2", "doubler", "bt", env)
print(type(f))
print(f())
local bad, err = load("return 1 +", "broken-chunk")
print(bad == nil)
print(string.find(err, "broken-chunk", 1, true) ~= nil)Key points
- load: load turns a code string into a function.
- Return values: load returns a function on success, or nil plus an error message on failure.
- Check first: Always check the first return value before calling the result.
- Chunkname: the chunkname is the name shown for the chunk in error messages.
- Modes: mode t allows text chunks only, mode b allows binary chunks only, and mode bt allows both.
- loadfile: loadfile loads a chunk from a file instead of from a string.
In this example, load builds a function named doubler in mode bt. The function reads answer from the passed environment table, so calling it prints 42. Then a broken chunk returns nil, and its error message contains broken-chunk.
Note
loading never runs the code, so nothing happens until the returned function is called.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does load return when the code string has a syntax error?