一、定义 c 模块
#include <lua.h>
#include <lauxlib.h>
static int add(lua_State *L) {
float a1 = lua_tonumber(L, 1);
float a2 = lua_tonumber(L, 2);
lua_pushnumber(L, a1 + a2);
return 1;
}
int luaopen_hello(lua_State *L) {
lua_register(L, "add", add);
return 1;
}
- luaopen_hello():入口函数,格式必须是:luaopen_文件名,lua 代码中 require 编译出来的 hello.so时,会立即去找 luaopen_hello()。
二、编译 c 模块
gcc -shared -fPIC hello.c -o hello.so
把编译好的 hello.so 文件,拷贝到 lua 能识别的目录,比如:lua-5.3.0/src。