Lua C API
基础概念
Lua C API 是 Lua 与 C/C++ 程序交互的接口,允许在 C 代码中嵌入 Lua 解释器、调用 Lua 函数以及管理 Lua 状态。
嵌入 Lua 到 C 程序
- 包含头文件
lua.h和lualib.h - 创建 Lua 状态:
lua_State *L = luaL_newstate(); - 打开标准库:
luaL_openlibs(L);
调用 C 函数
- 在 C 中定义函数:
c
static int l_my_function(lua_State *L) {
// 函数实现
return 1;
}- 注册函数到 Lua:
c
lua_register(L, "my_function", l_my_function);常用 API 函数
lua_pushnumber(L, n):将数字压入栈lua_tostring(L, index):获取字符串lua_pcall(L, nargs, nresults, errfunc):调用函数
错误处理
使用 lua_pcall 的 errfunc 参数或 luaL_error 函数处理错误。