一、定義 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。