Claude
Skills
Sign in
Back

Lua C Integration

Included with Lifetime
$97 forever

Use when lua C API for extending Lua with native code including stack operations, calling C from Lua, calling Lua from C, creating C modules, userdata types, metatables in C, and performance optimization techniques.

Backend & APIs

What this skill does


# Lua C Integration

## Introduction

Lua's C API enables seamless integration with C code, allowing developers to
extend Lua with high-performance native functionality or embed Lua as a scripting
engine within C applications. This bidirectional integration makes Lua ideal for
performance-critical applications requiring scripting capabilities.

The C API operates through a virtual stack for passing values between Lua and C,
with functions for manipulating Lua values, calling functions, and managing
memory. Understanding stack operations and Lua's data model is essential for
safe, efficient C integration.

This skill covers the Lua stack, calling C from Lua, calling Lua from C,
creating C modules, userdata and metatables, error handling, memory management,
and performance optimization patterns.

## Lua Stack Fundamentals

The Lua-C API uses a virtual stack for all value exchange between Lua and C,
requiring understanding of push/pop operations.

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

// Basic stack operations
void demonstrate_stack(lua_State *L) {
    // Push values onto stack
    lua_pushinteger(L, 42);           // Stack: 42
    lua_pushnumber(L, 3.14);          // Stack: 42 | 3.14
    lua_pushstring(L, "hello");       // Stack: 42 | 3.14 | "hello"
    lua_pushboolean(L, 1);            // Stack: 42 | 3.14 | "hello" | true
    lua_pushnil(L);                   // Stack: 42 | 3.14 | "hello" | true | nil

    // Get stack size
    int top = lua_gettop(L);          // Returns 5

    // Access values by index (1-based)
    lua_Integer i = lua_tointeger(L, 1);      // 42 (index from bottom)
    lua_Number n = lua_tonumber(L, 2);        // 3.14
    const char *s = lua_tostring(L, 3);       // "hello"
    int b = lua_toboolean(L, 4);              // 1 (true)

    // Negative indices (from top)
    lua_Number n2 = lua_tonumber(L, -4);      // 3.14 (4th from top)
    const char *s2 = lua_tostring(L, -3);     // "hello" (3rd from top)

    // Type checking
    if (lua_isnumber(L, 1)) {
        // Handle number
    }
    if (lua_isstring(L, 3)) {
        // Handle string
    }

    // Remove elements
    lua_pop(L, 1);                    // Remove top element (nil)
    lua_remove(L, 2);                 // Remove element at index 2 (3.14)

    // Replace element
    lua_pushstring(L, "world");
    lua_replace(L, 3);                // Replace index 3 with "world"

    // Clear stack
    lua_settop(L, 0);                 // Empty the stack
}

// Stack manipulation patterns
void stack_patterns(lua_State *L) {
    // Insert at specific position
    lua_pushstring(L, "new value");
    lua_insert(L, 1);                 // Insert at bottom

    // Copy element
    lua_pushvalue(L, 1);              // Duplicate element at index 1

    // Rotate elements
    lua_rotate(L, 1, 2);              // Rotate 2 elements starting from index 1

    // Check stack space
    if (!lua_checkstack(L, 100)) {
        // Failed to allocate stack space
    }

    // Absolute index (doesn't change with stack modifications)
    int abs_idx = lua_absindex(L, -1);
}

// Type checking helper
int check_arguments(lua_State *L) {
    int argc = lua_gettop(L);

    if (argc < 2) {
        return luaL_error(L, "Expected at least 2 arguments");
    }

    if (!lua_isnumber(L, 1)) {
        return luaL_error(L, "Argument 1 must be a number");
    }

    if (!lua_isstring(L, 2)) {
        return luaL_error(L, "Argument 2 must be a string");
    }

    return 0;
}

// Table operations
void table_operations(lua_State *L) {
    // Create table
    lua_newtable(L);                  // Stack: {}

    // Set field: table["key"] = "value"
    lua_pushstring(L, "value");
    lua_setfield(L, -2, "key");

    // Get field: value = table["key"]
    lua_getfield(L, -1, "key");
    const char *value = lua_tostring(L, -1);
    lua_pop(L, 1);

    // Set with arbitrary key
    lua_pushstring(L, "key2");
    lua_pushinteger(L, 42);
    lua_settable(L, -3);              // table[key2] = 42

    // Array-style: table[1] = "first"
    lua_pushinteger(L, 1);
    lua_pushstring(L, "first");
    lua_settable(L, -3);

    // Rawset/rawget (bypass metamethods)
    lua_pushstring(L, "rawkey");
    lua_pushstring(L, "rawvalue");
    lua_rawset(L, -3);

    // Table length
    lua_len(L, -1);
    lua_Integer len = lua_tointeger(L, -1);
    lua_pop(L, 1);
}

// Global variables
void global_operations(lua_State *L) {
    // Set global: my_global = 42
    lua_pushinteger(L, 42);
    lua_setglobal(L, "my_global");

    // Get global: value = my_global
    lua_getglobal(L, "my_global");
    lua_Integer value = lua_tointeger(L, -1);
    lua_pop(L, 1);
}
```

Master stack operations for efficient C-Lua value exchange and avoid stack
overflow through proper cleanup.

## Calling C Functions from Lua

C functions follow specific signatures and conventions to be callable from Lua
scripts.

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

// Basic C function callable from Lua
// int my_function(lua_State *L)
// Returns number of return values pushed onto stack
static int add(lua_State *L) {
    // Get arguments
    lua_Number a = luaL_checknumber(L, 1);
    lua_Number b = luaL_checknumber(L, 2);

    // Compute result
    lua_Number result = a + b;

    // Push result
    lua_pushnumber(L, result);

    // Return number of results
    return 1;
}

// Multiple return values
static int divide_with_remainder(lua_State *L) {
    lua_Integer a = luaL_checkinteger(L, 1);
    lua_Integer b = luaL_checkinteger(L, 2);

    if (b == 0) {
        return luaL_error(L, "Division by zero");
    }

    lua_pushinteger(L, a / b);        // Quotient
    lua_pushinteger(L, a % b);        // Remainder

    return 2;  // Return 2 values
}

// Optional arguments with defaults
static int greet(lua_State *L) {
    const char *name = luaL_optstring(L, 1, "World");
    lua_pushfstring(L, "Hello, %s!", name);
    return 1;
}

// Table as argument
static int sum_table(lua_State *L) {
    luaL_checktype(L, 1, LUA_TTABLE);

    lua_Number sum = 0;
    lua_Integer len = luaL_len(L, 1);

    for (lua_Integer i = 1; i <= len; i++) {
        lua_geti(L, 1, i);  // Get table[i]
        sum += lua_tonumber(L, -1);
        lua_pop(L, 1);
    }

    lua_pushnumber(L, sum);
    return 1;
}

// Returning a table
static int create_point(lua_State *L) {
    lua_Number x = luaL_checknumber(L, 1);
    lua_Number y = luaL_checknumber(L, 2);

    lua_newtable(L);

    lua_pushnumber(L, x);
    lua_setfield(L, -2, "x");

    lua_pushnumber(L, y);
    lua_setfield(L, -2, "y");

    return 1;
}

// Variadic arguments
static int print_all(lua_State *L) {
    int n = lua_gettop(L);  // Number of arguments

    for (int i = 1; i <= n; i++) {
        const char *str = luaL_tolstring(L, i, NULL);
        printf("%s\n", str);
        lua_pop(L, 1);  // Pop string from luaL_tolstring
    }

    return 0;
}

// Function with callback
static int each(lua_State *L) {
    luaL_checktype(L, 1, LUA_TTABLE);
    luaL_checktype(L, 2, LUA_TFUNCTION);

    lua_Integer len = luaL_len(L, 1);

    for (lua_Integer i = 1; i <= len; i++) {
        lua_pushvalue(L, 2);      // Push function
        lua_geti(L, 1, i);        // Push table[i]
        lua_pushinteger(L, i);    // Push index

        // Call function with 2 arguments
        if (lua_pcall(L, 2, 0, 0) != LUA_OK) {
            return lua_error(L);
        }
    }

    return 0;
}

// Register functions
static const luaL_Reg mylib[] = {
    {"add", add},
    {"divide_with_remainder", divide_with_remainder},
    {"greet", greet},
    {"sum_table", sum_table},
    {"create_point", create_point},
    {"print_all", print_all},
    {"each", each},
    {NULL, NULL}  // Sentinel
};

// Library initialization
int luaopen_mylib(lua_State *L) {
    luaL_newlib(L, mylib);
    return 1;
}

// Alternative registration
void register_functions(lua_State *L) {
    lua_register(L, "add", add);
    lua_register(L, "greet", g

Related in Backend & APIs