主题
Lua 与 C 的交互
Lua 作为嵌入式脚本语言,提供了强大的 C API,可以在 C/C++ 中嵌入 Lua,或者让 Lua 调用 C 函数,实现高性能扩展。
🧩 在 Lua 中调用 C 函数
假设我们有一个 C 动态库 mylib
,包含函数:
c
// mylib.c
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
编译生成共享库:
bash
gcc -shared -fPIC -o mylib.so mylib.c
Lua 中使用 ffi
调用(需要 LuaJIT):
lua
local ffi = require("ffi")
ffi.cdef[[
int add(int a, int b);
]]
local lib = ffi.load("./mylib.so")
print(lib.add(3, 5)) -- 输出 8
🔗 在 C 中嵌入 Lua
C 程序中可以嵌入 Lua 解释器,执行 Lua 脚本:
c
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
int main() {
lua_State *L = luaL_newstate(); // 创建 Lua 状态机
luaL_openlibs(L); // 打开标准库
if (luaL_dofile(L, "script.lua") != LUA_OK) {
const char *err = lua_tostring(L, -1);
printf("Error: %s\n", err);
}
lua_close(L);
return 0;
}
🧰 C 调用 Lua 函数
C 可以调用 Lua 脚本中的函数:
c
lua_getglobal(L, "greet"); // 获取 Lua 全局函数
lua_pushstring(L, "Alice"); // 压入参数
lua_pcall(L, 1, 0, 0); // 调用函数
Lua 代码 script.lua
:
lua
function greet(name)
print("Hello, " .. name)
end
🧩 Lua 注册 C 函数
在 C 中可以把函数注册到 Lua,使 Lua 可以直接调用:
c
int l_add(lua_State *L) {
int a = luaL_checkinteger(L, 1);
int b = luaL_checkinteger(L, 2);
lua_pushinteger(L, a + b);
return 1; // 返回值数量
}
lua_register(L, "add", l_add); // Lua 脚本中调用 add(3,5)
Lua 调用:
lua
print(add(3, 5)) -- 输出 8
🧠 小结
- Lua 可以调用 C 函数(LuaJIT 可用 ffi)
- C 程序可嵌入 Lua 解释器,执行 Lua 脚本
- C 可以注册函数,让 Lua 调用,实现混合编程
- Lua 与 C 的结合可以提高性能,扩展功能