扩展Lua接口

Lua 是巴西研究小组开发的一个灵活小巧的脚本语言,整个编译后的静态库才400多K,便于嵌入应用程序中,扩展程序功能。常用于游戏开发中,nginx的openresty项目也让lua更加流行。

Lua语法与python比较类似,支持自动垃圾回收,面向对象编程。

一. 扩展lua接口

lua没有提供sleep()和msleep()实现,我们可以提供动态库给lua调用,代码如下:

#include <unistd.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

// sleep实现
static int sleep_c( lua_State *l )
{
	long sec = lua_tointeger( l, -1 );
	sleep( sec );
	return 0;
}

// msleep实现
static int msleep_c( lua_State *l )
{
	long sec = lua_tointeger( l, -1 );
	usleep( sec*1000 );
	return 0;
}

// 声明模块函数集合
static const struct luaL_Reg libs[] = {
	{ "sleep", sleep_c },
	{ "msleep", msleep_c },
	{ NULL, NULL }
};


// 注册函数
int luaopen_myutil( lua_State *l )
{
	luaL_register( l, "myutil", libs );	// 库名称与luaopen_xxx一致
	return 1;
}

编译:liblua.a 需添加-fPIC选项,否则上述库会编译出错。

gcc -fPIC -shared -o myutil.so sleep.c -I. -I/usr/local/include -L/usr/local/lib -llua 

lua调用:

require "myutil"
local start = os.time()
print( "Start: ", start )
myutil.sleep(2)
local mid = os.time()
print( "End: "..mid )

动态库路径:将myutil.so库放在下面任意目录,均可正常执行:

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> print(package.cpath)
./?.so;/usr/lib64/lua/5.1/?.so;/usr/lib64/lua/5.1/loadall.so

参考链接:

http://www.troubleshooters.com/codecorn/lua/lua_lua_calls_c.htm#_Make_an_msleep_Function

猜你喜欢

转载自tcspecial.iteye.com/blog/2380072
今日推荐