lua与C交互(6):lua调用C函数

lua要调用的C函数有一个一致的签名:

typedef int (*lua_CFunction) (lua_State *L);

函数的返回值表示函数的返回值个数,lua与C通过lua虚拟机中的栈来传递参数和返回参数。

即C中的函数应该定义为:

int testfunc(lua_State* L)
{
	printf("testfunc from C");
	return 0;
}

return 0:表示函数没有返回值。

简单的例子CC代码:

int main()
{
	lua_State* L = luaL_newstate();  /* create state */
	if (L == NULL) {
		printf("lua state build error.\n");
		return 1;
	}
	luaL_openlibs(L);

	lua_pushcfunction(L, testfunc);
	lua_setglobal(L, "testfunc");

	luaL_dofile(L, "tfunc.lua");

	std::cin.get();
	lua_close(L);

	return 0;
}

简单的例子lua代码:

print("print from tfunc lua.")

testfunc()

下面以sum函数为例子来说明lua中调用C函数有多个参数和多个返回的情况:

lua代码为:

print("print from tfunc lua.")

testfunc()

total, avg = sum(1,2,3,4,5)
print(total, avg)

CC代码为:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>

#include "lua.hpp"

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

static void stackDump(lua_State* L)
{
	static int count = 0;
	printf("begin dump lua stack:%d\n", count);
	int top = lua_gettop(L);
	for (int i = top; i > 0; --i)
	{
		int t = lua_type(L, i);
		switch (t)
		{
		case LUA_TSTRING:
			printf("%s\n", lua_tostring(L, i));
			break;
		case LUA_TBOOLEAN:
			printf(lua_toboolean(L, i) ? "true\n" : "false\n");
			break;
		case LUA_TNUMBER:
			printf("%g\n", lua_tonumber(L, i));
			break;
		default:
			printf("%s\n", lua_typename(L, t));
			break;
		}
	}
	++count;
}

int testfunc(lua_State* L)
{
	printf("testfunc from C");
	return 0;
}

int sum(lua_State* L)
{
	//lua中传过来的参数在栈中,我们可以从栈顶到栈底打印一下内容
	stackDump(L);
	int total = 0;
	int n = lua_gettop(L);
	for (int i = n; i > 0; --i)
	{
		total += lua_tointeger(L, i);
	}
	//通过栈将返回传回lua
	lua_pushinteger(L, total);
	lua_pushinteger(L, total / n);
	return 2; // 返回2个参数
}

int main()
{
	lua_State* L = luaL_newstate();  /* create state */
	if (L == NULL) {
		printf("lua state build error.\n");
		return 1;
	}
	luaL_openlibs(L);

	lua_pushcfunction(L, testfunc); //将函数压入栈
	lua_setglobal(L, "testfunc"); //将函数调出栈,并赋值为testfunc

	lua_pushcfunction(L, sum);
	lua_setglobal(L, "sum");

	luaL_dofile(L, "tfunc.lua");

	std::cin.get();
	lua_close(L);

	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一尺丈量

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

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

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

打赏作者

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

抵扣说明:

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

余额充值