lua入门教程:第九章 C API 另一种注册方式

还有另外一种往lua中注册函数的方法,直接把函数编译在dll或者so中,当require "xx"后就会自动的加载dll中的函数,注册到lua中去,看下我们是如何加载这一个过程的。

tbLib.h

#ifndef _TBLIB_H
#define _TBLIB_H

#ifdef __cplusplus
extern "C" {
#endif

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

#ifdef TBLIB_EXPORTS
#define TBLIB_EXPORTS __declspec(dllexport) 
#else
#define TBLIB_EXPORTS __declspec(dllimport)
#endif

// 全局的函数,用于导出,内部完成注册和初始化功能
TBLIB_EXPORTS int luaopen_tbLib(lua_State *L);

#ifdef __cplusplus
}
#endif
#endif

这里导出luaopen_tbLib函数,这个函数在lua中require "xx"后会自动的加载,看看luaopen_tbLib做了哪些事情。

tbLib.c

#include <stdio.h>
#include "tbLib.h"

static int test(lua_State *L)
{
	printf("abc");
	lua_pushnumber(L, 10);

	return 1;
}

static const struct luaL_Reg myLib[] = 
{
	{"test", test},
	{NULL, NULL}
};

int luaopen_tbLib(lua_State *L)
{
	luaL_register(L, "tbLib", myLib);
	return 1; // 把表压入了栈中,所以就需要返回1
}

同样的我们看看luaL_register中做了什么事情。

lauxlib.h中,定义着luaL_register为:

#define luaL_register(L,n,l)	(luaL_openlib(L,(n),(l),0))

可以在继续跟进 luaL_openlib,可以发现做的事情也是把函数压入的栈中,然后进行设置变量值,并它表的名字命名为我们所取的函数名。

可以这样来调用lua代码:

require "testLib"
local a = testLib.test()
print(a)

在这里a的变量为 10。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

go2coding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值