0Pricing
Lua Academy · Lesson

Registering C Functions in Lua

Expose C functions to Lua scripts using luaL_register and lua_pushcfunction.

Overview

C functions can be exposed to Lua scripts. They must have the signature int myFunc(lua_State *L). They read arguments from the stack and push return values.

C Function Signature

Every function callable from Lua is a lua_CFunction: it takes a lua_State*, reads arguments, pushes results, and returns the count of results.

// C code
static int l_add(lua_State *L) {
  double a = luaL_checknumber(L, 1);
  double b = luaL_checknumber(L, 2);
  lua_pushnumber(L, a + b);
  return 1;  // one result
}

All lessons in this course

  1. The Lua C API Stack Model
  2. Calling Lua Functions from C
  3. Registering C Functions in Lua
  4. Managing State and Error Handling
← Back to Lua Academy