3.10 – Loading Lua Chunks

You can load a Lua chunk with lua_load:

  1. typedef const char * (*lua_Chunkreader)
  2. (lua_State *L, void *data, size_t *size);
  3.  
  4. int lua_load (lua_State *L, lua_Chunkreader reader, void *data,
  5. const char *chunkname);

The return values of lua_load are:

  • 0 —- no errors;
  • LUA_ERRSYNTAX —- syntax error during pre-compilation.
  • LUA_ERRMEM —- memory allocation error.

If there are no errors, lua_load pushes the compiled chunk as a Lua function on top of the stack. Otherwise, it pushes an error message.

lua_load automatically detects whether the chunk is text or binary, and loads it accordingly (see program luac).

lua_load uses a user-supplied reader function to read the chunk. Everytime it needs another piece of the chunk, lua_load calls the reader, passing along its data parameter. The reader must return a pointer to a block of memory with a new piece of the chunk and set size to the block size. To signal the end of the chunk, the reader returns NULL. The reader function may return pieces of any size greater than zero.

In the current implementation, the reader function cannot call any Lua function; to ensure that, it always receives NULL as the Lua state.

The chunkname is used for error messages and debug information (see 4).

See the auxiliary library (lauxlib.c) for examples of how to use lua_load and for some ready-to-use functions to load chunks from files and strings.