加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在Lua表中注册C函数

发布时间:2020-12-16 06:02:33 所属栏目:百科 来源:网络整理
导读:如何在Lua中注册C函数,但不是在全局上下文中,而是作为表字段? 解决方法 这是 luaL_register() 打算做的一个或多个功能.规范使用是用C编写的模块的一部分: /* actual definitions of modA() and modB() are left as an exercise. *//* list of functions in
如何在Lua中注册C函数,但不是在全局上下文中,而是作为表字段?

解决方法

这是 luaL_register()打算做的一个或多个功能.规范使用是用C编写的模块的一部分:
/* actual definitions of modA() and modB() are left as an exercise. */

/* list of functions in the module */
static const luaL_reg modfuncs[] =
{
    { "a",modA},{ "b",modB},{ NULL,NULL }
};

/* module loader function called eventually by require"mod" */  
int luaopen_mod(lua_State *L) {
    luaL_register(L,"mod",modfuncs);
    return 1;
}

这里创建一个名为“mod”的模块,它有两个名为mod.a和mod.b的函数.

引用luaL_register(L,libname,l)的手册:

When called with libname equal to
NULL,it simply registers all
functions in the list l (see 07001)
into the table on the top of the
stack.

When called with a non-null libname,
luaL_register creates a new table t,
sets it as the value of the global
variable libname,sets it as the value
of package.loaded[libname],and
registers on it all functions in the
list l. If there is a table in
package.loaded[libname] or in variable
libname,reuses this table instead of
creating a new one.

In any case the function leaves the table on the top of the stack.

只要表位于堆栈的顶部,luaL_register()可以用于将C函数放在任何表中,通过传递NULL作为其第二个参数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读