Lua C Integration
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.
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", gRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.