The ultimate superpower of Lua is its seamless integration with C and C++. Lua does not communicate with C via complex Foreign Function Interfaces (FFI); it communicates via a simple, bidirectional Virtual Stack.
The Virtual Stack Architecture
Because C has static typing and manual memory management while Lua has dynamic typing and garbage collection, direct pointer sharing is unsafe. Instead, all data exchange between C and Lua occurs through the Lua Virtual Stack:
Virtual Stack (lua_State *L)
Top Index:
[ +3 / -1 ] --> String: "developer"
[ +2 / -2 ] --> Number: 42.0
[ +1 / -3 ] --> Table: { ... }
Base Index
- Positive Indices: Count from the bottom (base) upwards (
1is first pushed). - Negative Indices: Count from the top downwards (
-1is the top of the stack).
Basic Stack Operations in C
// Pushing values onto the stack (C -> Lua)
lua_pushnumber(L, 3.14159);
lua_pushstring(L, "CodeAcademix");
lua_pushboolean(L, 1);
// Reading values from the stack (Lua -> C)
if (lua_isstring(L, -1)) {
const char *str = lua_tostring(L, -1);
}
if (lua_isnumber(L, -2)) {
double num = lua_tonumber(L, -2);
}
// Removing top element
lua_pop(L, 1);
Exposing C Functions to Lua
A C function callable from Lua must adhere to the exact signature: int function_name(lua_State *L)
It reads its arguments from the stack, pushes its return values onto the stack, and returns an integer specifying how many return values were pushed:
// Fast native C implementation of high-precision distance calculation
#include <lua.h>
#include <lauxlib.h>
#include <math.h>
static int l_calculate_distance(lua_State *L) {
// 1. Read parameters from stack
double x1 = luaL_checknumber(L, 1);
double y1 = luaL_checknumber(L, 2);
double x2 = luaL_checknumber(L, 3);
double y2 = luaL_checknumber(L, 4);
// 2. Compute in native C
double dx = x2 - x1;
double dy = y2 - y1;
double dist = sqrt(dx * dx + dy * dy);
// 3. Push result back onto stack
lua_pushnumber(L, dist);
// 4. Return number of results on stack
return 1;
}
// Register function into Lua environment
void register_native_utils(lua_State *L) {
lua_pushcfunction(L, l_calculate_distance);
lua_setglobal(L, "calculateDistance");
}
Now in Lua, you can call it natively:
local distance = calculateDistance(0, 0, 30, 40)
print("Distance computed in native C: " .. distance) -- 50.0
Exercises
- Write a C function exposed to Lua that takes an array table of numbers and returns their sum and average simultaneously.
- Explain how the virtual stack prevents C pointers from interfering with Lua's garbage collector.
- What is the difference between
lua_call()(unprotected) andlua_pcall()(protected call with error handling)?