As the documentation says, passing load
a function will cause load
to call this function again and again, building a string from its results.
A simple example would be a function that when called prompts the user for a line of input. If the return value of this function is a nonzero length string, then it is concatenated to the string being built by load
. Returning ''
, nil
, or nothing causes load
to stop calling the function.
load
then attempts to create a chunk from the string it has built.
--[[ Example of loading a chunk from a string ]]
local chunk = load('print("Hello world")')
-- can be called as `chunk()`, if there are no syntax errors
--[[ Example of loading a chunk from a generating function ]]
local chunk, msg = load(function ()
io.write('> ')
return io.read('*l')
end)
-- catch syntax errors, e.g., `print(a + )`
if chunk then
-- catch runtime errors, e.g., `print(nil + nil)`
msg = select(2, pcall(chunk))
end
-- handle any errors; here we simply propagate it
if msg then
error(msg)
end
In use:
$ lua chunks.lua
> print('hello world')
> print(51)
>
hello world
51
We can see the third line was empty, which ended the calls to the function.
We can very roughly define the functionality like this:
local function chunk_from_func(fn)
local chunkstring = ''
while true do
local s = fn()
if not s or s == '' then
break
end
chunkstring = chunkstring .. s
end
return chunk_from_string(chunkstring)
end