lua添加自定义模块的步骤

以下方法在lua 5.2.4版本下成功实现:

 

1. lua.c为所有函数的主程序,参考Makefile的编译链接
2. lua.c中
int main (int argc, char **argv) {

/* call 'pmain' in protected mode */
lua_pushcfunction(L, &pmain);

}
static int pmain (lua_State *L) {
...
luaL_openlibs(L); /* open libraries */
...
}

3. linit.c中
static const luaL_Reg loadedlibs[] = {
{"_G", luaopen_base},
{LUA_LOADLIBNAME, luaopen_package},
{LUA_COLIBNAME, luaopen_coroutine},
{LUA_TABLIBNAME, luaopen_table},
{LUA_IOLIBNAME, luaopen_io},
{LUA_OSLIBNAME, luaopen_os},
{LUA_STRLIBNAME, luaopen_string},
{LUA_BITLIBNAME, luaopen_bit32},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_DBLIBNAME, luaopen_debug},

{LUA_LOADMYLIBNAME, luaopen_mypackage},

{NULL, NULL}
};

 

4. lualib.h中
...
#define LUA_LOADLIBNAME "package"
LUAMOD_API int (luaopen_package) (lua_State *L);

#define LUA_LOADMYLIBNAME "mypackage"
LUAMOD_API int (luaopen_mypackage) (lua_State *L);

/* open all previous libraries */
LUALIB_API void (luaL_openlibs) (lua_State *L);
...

5. myloadlib.c中
...
static int printhelloworld (lua_State *L) {
printf("[mypackage] hello world\n");
return 0;
}

static int myadd (lua_State *L) {
printf("%d %d\n", (int)luaL_checknumber(L, 1), (int)luaL_checknumber(L, 2));
lua_pushnumber(L, (int)luaL_checknumber(L, 1) + (int)luaL_checknumber(L, 2));
return 1;
}


static const luaL_Reg my_funcs[] = {
{"printhelloworld", printhelloworld},
{"myadd", myadd},
{NULL, NULL}
};


LUAMOD_API int luaopen_mypackage (lua_State *L) {
 
/* create `package' table */
luaL_newlib(L, my_funcs);}
return 1;


}

6. Makefile中
...
LIB_O= lauxlib.o lbaselib.o lbitlib.o lcorolib.o ldblib.o liolib.o \
lmathlib.o loslib.o lstrlib.o ltablib.o loadlib.o myloadlib.o linit.o
...
myloadlib.o: myloadlib.c lua.h luaconf.h lauxlib.h lualib.h
...

7. lua中调用
function helloworld()
mypackage.printhelloworld();
print(mypackage.myadd(11,222));
end

转载于:https://www.cnblogs.com/hugb/p/6892558.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值