Reading Lua variables from C
It's very easy to read and write Lua variables from C. Because of this, Lua is often used as a configuration language or to save and load the state of a program. The Lua runtime will parse and interpret files for you, removing the need for manual parsing. And the syntax of Lua lends itself very well to these kinds of tasks. In this section, we're going to explore how to read Lua variables that are used as configuration data.
Loading a Lua file
To read a Lua variable in C, you will need to load the Lua file with int luaL_loadfile(lua_State*, const char*)
. The resulting chunk will then need to be executed with lua_pcall(lua_State*, int, int, int, int)
. After the Lua chunk is loaded and executed, any variables it declared can be read. The lua_pcall
function will be described in more detail in the Calling Lua functions from C section of this chapter.
The luaL_loadfile
function returns 0 on success, or one of the following enumerations on failure: LUA_ERRSYNTAX
, LUA_ERRMEM...