写了一个测试Lua调用的C库,如下:
头文件:
#ifndef __C_LIB_H_FILE__
#define __C_LIB_H_FILE__
extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
__attribute__ ((visibility("default")))
int luaopen_libtestlib( lua_State *l );
}
//int mymax( lua_State * l );
#endif // __C_LIB_H_FILE__
cpp文件
#include "clib.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
int mymax( lua_State * l )
{
int a = lua_tointeger( l, 1 );
int b = lua_tointeger( l, 2 );
if ( a > b )
{
lua_pushinteger( l, a );
}else
{
lua_pushinteger( l, b );
}
return 1;
}
const struct luaL_Reg funcs[]=
{
{"mymax", mymax},
{ NULL, NULL}
};
extern "C"
__attribute__ ((visibility("default")))
int luaopen_libtestlib( lua_State *l )
{
luaL_register( l, "testlib", funcs );
return 1;
}
然后编译,用的lua脚本如下:
function callc()
local testlib = require("libtestlib")
print ( testlib.mymax( 12, 6 ) )
end
print("C path:", package.cpath )
print("hello module")
callc()
调用方式:生成的库和lua脚本在同一个目录,调用方式如下:
lua usec.lua
然后就发现死活找不到写C函数库,后来使用assert()把rquire("libtestlib")包住,发现输出信息是无法找到链接库,为什么呢?
输出package.cpath,报错,说package是个nil值。
后来打开synaptic,发现安装的lua包是不完整的,找了个lua5.1安装后,才正确输出结果。