Skip to content

Lesson 5 of 9 · 28m

The Lua C API: Stacks, Calls, and Lifetime Rules

How host code actually drives Lua: lua_State, the stack discipline, protected calls, references, and the memory mistakes that create impossible crashes.

The Lua C API is small, consistent, and merciless. Everything happens through a stack owned by a lua_State. Once that clicks, the API becomes predictable. If it never clicks, every binding becomes a memory-corruption story told six months later in production.

Creating a state and running code

lua_State *L = luaL_newstate();
luaL_openlibs(L);
if (luaL_dostring(L, "return 1 + 2") != LUA_OK) {
  fprintf(stderr, "lua error: %s\n", lua_tostring(L, -1));
  lua_pop(L, 1);
}
lua_close(L);

luaL_newstate creates the interpreter, luaL_openlibs installs the standard libraries, and lua_close destroys everything owned by that state. In hardened embeddings, use lua_newstate with a custom allocator so memory usage is accountable.

The stack is positional

Values are addressed by index: positive numbers from the bottom, negative numbers from the top. After pushing a function and two arguments, the stack is your calling convention.

lua_getglobal(L, "spawn_enemy");  -- function at -1
lua_pushstring(L, "imp");         -- arg 1
lua_pushinteger(L, 12);           -- arg 2
if (lua_pcall(L, 2, 1, 0) != LUA_OK) {
  const char *err = lua_tostring(L, -1);
  log_script_error(err);
  lua_pop(L, 1);
} else {
  int id = (int)lua_tointeger(L, -1);
  lua_pop(L, 1);
}

The number of arguments and results is explicit. lua_pcall is the protected version of lua_call; use it for script-controlled code. If it fails, the error object is on the stack and you must pop it.

References cross the boundary safely

Do not keep a raw Lua table pointer in C. Store it in the registry:

lua_pushvalue(L, -1);
int ref = luaL_ref(L, LUA_REGISTRYINDEX);

lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
/* use the value */
luaL_unref(L, LUA_REGISTRYINDEX, ref);

The registry keeps Lua objects alive. Forgetting luaL_unref leaks; using the wrong reference after close crashes. Ownership must be boring enough that a tired maintainer can audit it.

Userdata is for native objects

Full userdata is memory managed by Lua; lightuserdata is just a pointer. Expose native resources as full userdata with a metatable and __gc finalizer. Validate the userdata type before casting. Never trust a script-supplied pointer-shaped value.

Field notes

  • Balance the stack. Write bindings that leave it exactly as documented; intermittent corruption usually means one branch forgot lua_pop.
  • lua_tolstring can convert numbers in place. Do not assume a value still has its original type after inspecting it.
  • Longjmp error handling means memory management discipline matters; C++ destructors do not automatically run across a Lua error. LuaJIT's API is Lua 5.1-shaped, so 5.4 integer and bitwise assumptions are not portable.

Was this lesson helpful?

Sign in to rate