Working with the C API

The Lua C API is efficient and lightweight. There are a few important header files we need to be familiar with before writing any C code. These files are the following:

  • lua.h: Provides all the functions needed to work with Lua. All functions in this file are prefixed with lua_.
  • luaxlib.h: Uses the public API exposed in lua.h to provide higher levels of abstraction for common tasks. All functions in this file are prefixed with luaL_.
  • lualib.h: Provides the standard Lua libraries. All functions in this file are also prefixed with luaL_.

Lua does not allocate any global memory. Instead it stores all of its states in a structure called lua_State. This structure contains everything that the Lua runtime needs to operate. Putting a mutex lock around your lua_State object is a fast and easy way to make sure any Lua instance is thread safe. It's perfectly valid to create multiple states and therefore multiple Lua runtimes in one application, though the use cases for this are scarce.

To create a new Lua state, call the luaL_newstate() function, which will return a pointer to a lua_State structure. This pointer needs to be passed to all future Lua API calls—this is how Lua knows what runtime it is working with. After your program is done running, destroy the state with the lua_close(lua_State*) function.

When you create a new Lua state, the standard Lua libraries are not automatically loaded. This can be problematic as Lua programmers will expect, as a minimum, that the standard Lua libraries will be available. You can load the standard libraries with the luaL_openlibs(lua_State*) function.

The code that follows demonstrates how to set up and destroy an embedded Lua runtime:

#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

int main(int argc, char** argv) {
// First, create a new lua state
lua_State *L = luaL_newstate();
// Next, load all the standard libraries
luaL_openlibs(L);

//Write code that interacts with the Lua runtime here

// Finally, destory the lua state
lua_close(L);
return 0;
}
Lua does not add #ifdef __cplusplus or extern "C" decorations to it's code. This means Lua can be compiled as C or as C++ code. Since C++ mangles function names, make sure to link to the right version of the library.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.70.247