Skip to content

Lesson 2 of 9 · 27m

The lua_State, the Stack, and the C API Contract

Learn the stack discipline behind lua_pcall, arguments, returns, references, and cleanup so embedded Lua calls stop corrupting state in production.

Most embedding bugs I have been called in to fix were not Lua bugs. They were stack-discipline bugs in C. A handler pushed arguments, hit an early return, forgot to pop results, and slowly turned the Lua stack into a junk drawer. The C API is small, but it is exacting: values live on a stack, indexes are positional, errors can leave values behind, and the caller owns cleanup. Treat that contract casually and the embedding becomes nondeterministic in the worst possible way.

The stack is the API

Lua and C exchange values through the stack belonging to a lua_State; -1 is the most recently pushed value.

lua_State *L = luaL_newstate();
if (L == NULL) return -1;
luaL_openlibs(L);
lua_getglobal(L, "on_request");  /* function */
lua_pushstring(L, path);         /* function, path */
if (lua_pcall(L, 1, 1, 0) != LUA_OK) {
    fprintf(stderr, "lua error: %s
", lua_tostring(L, -1));
    lua_pop(L, 1);
} else {
    int allowed = lua_toboolean(L, -1);
    lua_pop(L, 1);
}
lua_close(L);

Push exactly what you mean, use exact argument and result counts, inspect errors, and leave the stack as you found it.

lua_pcall is not optional decoration

lua_call propagates errors through a long jump; lua_pcall returns control to the host:

if (lua_pcall(L, 2, 1, 0) != LUA_OK) {
    log_lua_error(lua_tostring(L, -1));
    lua_pop(L, 1);
}

Errors are not always strings. Log defensively and do not use the error shape for control flow.

Registry references solve lifetime, not ownership confusion

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

A reference keeps a Lua object alive; it does not define the validity or ownership of host resources behind handles.

One state is not a concurrency model

A lua_State is not thread-safe. Do not call into the same state from multiple host threads without external serialization. If you need parallelism, use separate states or a carefully designed worker model. Coroutines inside one state provide cooperative control flow, not simultaneous execution.

Field notes

  • lua_tostring can convert numbers and mutate stack values; for complex paths, use lua_gettop/lua_settop as a balance check.
  • Pop error objects even in failure paths, or the next script call inherits contaminated state.
  • A registry reference is a GC root; forgetting luaL_unref is a memory leak.
  • Never let a Lua state become shared mutable infrastructure across unrelated threads without a locking design.

Was this lesson helpful?

Sign in to rate