load

Loads a chunk by calling a function repeatedly

Prototype

f = load (loader, debugname)

Description

Loads a chunk using function loader to get its pieces. Each call to loader must return a string that concatenates with previous results. A return of nil (or no value) signals the end of the chunk.

If there are no errors, returns the compiled chunk as a function; otherwise, returns nil plus the error message. The environment of the returned function is the global environment.

This could be used to gradually build up a chunk (for example from a network), or to write a preprocessor that reads in a file, preprocess it (like the C preprocessor) and returns the altered code to the Lua interpreter.

The example below shows generating code from entries in a table.

function getcode (t)
local pos = 0
  local function iterator (s)
    pos = pos + 1
    return t [pos]
  end -- iterator
  return iterator
end -- getcode


code = {
  "local a = 1 ",
  "print ('a =', a) ",
  "print 'done.'"
  }
  
assert (load (getcode (code))) ()

Lua functions

Topics