width = 100
height = 101
hello = 95050
function add(a, b)
return a + b + 100
end
#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
int main(){
lua_State *L = luaL_newstate();
luaL_openlibs(L);
if(luaL_loadfile(L, "test.lua") || lua_pcall(L, 0, 0, 0)){
printf("error");
return -1;
}
lua_getglobal(L, "width");
lua_getglobal(L, "height");
lua_getglobal(L, "hello");
printf("width = %d\n", lua_tointeger(L, -3));
printf("height = %d\n", lua_tointeger(L, -2));
printf("%d\n", lua_tointeger(L, -1));
lua_getglobal(L, "add");
lua_pushnumber(L, 100);
lua_pushnumber(L, 180);
//2表明参数个数,1表明返回结果个数
int ret = lua_pcall(L, 2, 1, 0);
if(ret){
//表明调用出错
}
if(lua_isnumber(L, -1)){
printf("%d", lua_tointeger(L, -1));
}
lua_close(L);
return 0;
}
gcc -lm -g -o test main.c ./liblua.a -ldl
./test
#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include <math.h>
static int
myadd(lua_State *L){
int a = luaL_checknumber(L, 1);
int b = luaL_checknumber(L, 2);
lua_pushnumber(L, a + b);
return 1;
}
static const struct luaL_Reg mylib [] = {
{"add", myadd},
{NULL, NULL}
};
int luaopen_mylib(lua_State *L){
luaL_newlib(L, mylib);
return 1;
}
local lib = require "mylib"
width = 100
height = 101
hello = 95050
print(lib.add(1, 400))
function add(a, b)
return a + b + 100
end
gcc mylib.c -fPIC -shared -o mylib.so
最主要的是GCC命令行的一个选项:
-shared该选项指定生成动态链接库(让链接器生成T类型的导出符号表,有时候也生成弱连
接W类型的导出符号),不用该标志外部程序没法链接。至关于一个可执行文件
-fPIC:表示编译为位置独立的代码,不用此选项的话编译后的代码是位置相关的因此动态载
入时是经过代码拷贝的方式来知足不一样进程的须要,而不能达到真正代码段共享的目的。
-L.:表示要链接的库在当前目录中
-ltest:编译器查找动态链接库时有隐含的命名规则,即在给出的名字前面加上lib,后面
加上.so来肯定库的名称
LD_LIBRARY_PATH:这个环境变量指示动态链接器能够装载动态库的路径。
固然若是有root权限的话,能够修改/etc/ld.so.conf文件,而后调用 /sbin/ldconfig
来达到一样的目的,不过若是没有root权限,那么只能采用输出LD_LIBRARY_PATH的方法
了。