1. main.c
-----------------
//动态库
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _cplusplus
extern "C"{
#endif
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
static void checktoptype(lua_State *L){
if(lua_isnumber(L, -1))
printf("number");
else if(lua_isstring(L, -1))
printf("string");
else if(lua_isfunction(L, -1))
printf("function");
else if(lua_isboolean(L, -1))
printf("boolean");
else if(lua_isnil(L, -1))
printf("nil");
else if(lua_istable(L, -1))
printf("table");
else
printf("userdata or thread");
}
static int l_print(lua_State *L){
int ress[100];
int i = 1;
int n = 0;
for(; i <= 100; i++){
if(lua_isnil(L,-1)||!lua_isnumber(L, -1)){
break;
}
ress[i-1] = lua_tonumber(L, -1);//获取number,这个函数不删栈元素
lua_pop(L, 1);
n++;
}
//把值传给lua,调用lua中的print
lua_getglobal(L, "print");//获取函数
for(i = 0; i < n; i++){
lua_pushnumber(L, ress[i]);//push参数
//printf("stack level = %d, n = %d\n", lua_gettop(L), n);
lua_insert(L,2);//调整输出顺序
}
if(lua_pcall(L, n, 0, 0)){
printf("错误,lua_pcall! %s",
lua_tostring(L, -1));
return 0;
}
return n;
}
static const struct luaL_Reg l_lib[] = {
{"luaprint", l_print},
{NULL, NULL}
};
int luaopen_llib(lua_State* L){
luaL_openlib(L, "llib", l_lib, 0);//第二个参数,似乎可以随意写什么都行。
//luaL_register(L, "llib", l_lib);
return 1;
}
#ifdef _cplusplus
}
#endif
----------------
main.lua
----------------
f = function(...)
for i,v in pairs(arg) do --另外发现lua5.2中arg失去了保存可变变量的功能
print(i,v)
end
end
f(1,2);
llib = require "llib"
llib.luaprint(12,24,36,48,59)
---------------
c动态库编译方法:gcc -fPIC -llua -lm -shared -o llib.so main.c
lua执行命令: lua main.lua