TExcelTAD
Home › Lua › Embedding Lua (C API)

Embedding Lua (C API)

Lua was designed as an extension language: a small library that a host program written in C (or C++, Rust, Go, C#…) links in so that users can script it. Neovim, Redis, nginx/OpenResty, Wireshark, game engines and many others work this way. The host and the scripts talk through the Lua C API, built around a virtual stack.

This lesson's C code is not runnable in the playground (it needs a C compiler and the Lua library), but the Lua side of each example is.

The smallest host

c
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

int main(void) {
    lua_State *L = luaL_newstate();   /* a new, independent interpreter */
    luaL_openlibs(L);                 /* load the standard libraries */

    if (luaL_dostring(L, "print('Hello from embedded Lua', 6 * 7)") != LUA_OK) {
        fprintf(stderr, "error: %s\n", lua_tostring(L, -1));
    }
    lua_close(L);
    return 0;
}
bash
$ cc host.c -o host $(pkg-config --cflags --libs lua5.4)
$ ./host
Hello from embedded Lua	42

A lua_State is a complete interpreter. A program can create several, fully isolated from each other (Redis, for example, uses one per server).

The stack

C and Lua exchange values through a stack. You push values, call functions that consume them, and read results by index: 1 is the bottom, -1 the top.

Function Effect
lua_pushinteger(L, n), lua_pushstring(L, s), lua_pushnumber, lua_pushboolean push a value
lua_getglobal(L, "name") push the value of a global
lua_setglobal(L, "name") pop the top value into a global
lua_tointeger(L, i), lua_tostring(L, i) read a stack slot
lua_pcall(L, nargs, nresults, msgh) call a function in protected mode
lua_pop(L, n) discard values
luaL_checkinteger(L, i) read an argument, raising a Lua error if it has the wrong type

Calling a Lua function from C

Suppose a game lets modders define how damage is calculated in rules.lua:

lua · try it yourself
-- rules.lua: written by the user / modder
function damage(attack, armour)
  local raw = attack * 2 - armour
  return math.max(raw, 1)
end

-- what the host's C code effectively does: call the global with two arguments
print(damage(30, 12), damage(5, 40))
48	1

The C side pushes the function and the arguments, calls, and reads the result:

c
lua_getglobal(L, "damage");          /* push the function   */
lua_pushinteger(L, 30);              /* push argument 1     */
lua_pushinteger(L, 12);              /* push argument 2     */
if (lua_pcall(L, 2, 1, 0) == LUA_OK) {         /* 2 args, 1 result */
    long long dmg = lua_tointeger(L, -1);
    lua_pop(L, 1);
    printf("damage = %lld\n", dmg);            /* damage = 48 */
} else {
    printf("script error: %s\n", lua_tostring(L, -1));
    lua_pop(L, 1);
}

Using lua_pcall instead of lua_call means an error in the user's script is reported instead of crashing the host.

Calling C from Lua

To expose a C function, write it with the lua_CFunction signature: it receives its arguments on the stack and returns how many results it pushed.

c
static int l_clamp(lua_State *L) {
    lua_Integer x  = luaL_checkinteger(L, 1);
    lua_Integer lo = luaL_checkinteger(L, 2);
    lua_Integer hi = luaL_checkinteger(L, 3);
    lua_pushinteger(L, x < lo ? lo : x > hi ? hi : x);
    return 1;                               /* one result */
}

static const luaL_Reg engine_funcs[] = {
    { "clamp", l_clamp },
    { NULL, NULL }
};

/* register as a module table: local engine = require("engine") */
int luaopen_engine(lua_State *L) {
    luaL_newlib(L, engine_funcs);
    return 1;
}

From the script's point of view, the result is an ordinary module. Here a Lua stand-in plays the role of the C library so you can see the script side run:

lua · try it yourself
package.preload["engine"] = function()     -- in a real host this is luaopen_engine
  return {
    clamp = function(x, lo, hi)
      assert(math.type(x) and math.type(lo) and math.type(hi), "integers expected")
      return math.max(lo, math.min(hi, x))
    end,
  }
end

local engine = require("engine")
print(engine.clamp(250, 0, 100), engine.clamp(-4, 0, 100))
100	0

Sandboxing scripts

Hosts often run untrusted scripts. Because globals are just a table, the host can give a script a custom environment containing only safe functions. In Lua itself this is the env argument of load:

lua · try it yourself
local safeEnv = {
  print = print,
  math = { floor = math.floor, max = math.max },
  string = { upper = string.upper },
}

local userScript = [[
  print(string.upper("hi"), math.max(3, 9))
  print(os, io, require)          -- not available here
]]

local chunk = load(userScript, "user", "t", safeEnv)
chunk()

local ok, err = pcall(load([[os.execute("rm -rf /")]], "evil", "t", safeEnv))
print(ok, err)
HI	9
nil	nil	nil
false	[string "evil"]:1: attempt to index a nil value (global 'os')

The "t" mode allows only text chunks (no precompiled bytecode, which could be crafted to break the VM). Real sandboxes also limit run time with debug.sethook or the host's own instruction counter.

Userdata

Host objects (a window, a sprite, a database connection) are exposed as userdata: a block of C memory with a metatable. The metatable's __index provides methods and __gc frees the C resource, which is why file:read() and file:close() look like ordinary Lua methods: io.open returns a userdata.

Test yourself

How do C and Lua pass values to each other in the C API?

  1. Through shared global C variables
  2. Through a virtual stack
  3. Through JSON strings
  4. Through files

Why should a host call scripts with lua_pcall rather than lua_call?

  1. It is faster
  2. Errors in the script are returned instead of aborting the host
  3. It allows coroutines
  4. It enables the JIT

Which load argument restricts which globals a chunk can see?

  1. The chunk name
  2. The mode
  3. The environment table env
  4. None; it is impossible