lua入门之4:lua调用c/c++库(函数压栈方式)

lua入门之四:lua调用c/c++库(函数压栈方式)

前面讲过lua载入dll的方式去调用函数库,下面介绍的是函数压栈的方式调用函数库,通过lua_register把函数注册到lua的栈中,lua_register的定义如下,

#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))

看了定义就知道,其实就是函数压栈,然后设置为全局变量,这样lua就可以调用它了。


// libforlua-2.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <math.h>

//lua头文件
#ifdef __cplusplus
extern "C" {
#include "lua.h"  
#include <lauxlib.h>   
#include <lualib.h>   
}  

#else

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

#endif


#pragma comment(lib, "lua51.lib")


static int math_abs(lua_State *L)
{
	//获取传入的参数
	lua_pushnumber(L, abs((int)luaL_checknumber(L, 1)));

	return 1;
}

static int math_cos(lua_State *L)
{

	lua_pushnumber(L, cos((double)luaL_checknumber(L, 1)));

	return 1;

}

static int math_sin(lua_State *L)
{

	lua_pushnumber(L, sin((double)luaL_checknumber(L, 1)));


	return 1;
}

static const luaL_reg mathlib[] = {
	{ "abs", math_abs },
	{ "cos", math_cos },
	{ "sin", math_sin },
	{ NULL, NULL }
};


static int ShowMessage(lua_State * L)
{
	lua_pushnumber(L, 1000);
	printf("show message and push 1000 \n");
	return -1;
}



int main(int argc, char** argv)
{
	lua_State* L = lua_open();

	luaL_openlibs(L);

	//	lua_register(L, "cos", math_cos);
	//	lua_register(L, "sin", math_sin);
	//	lua_register(L, "abs", math_abs);


	//#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))
	luaL_register(L, "DY_MATH", mathlib);
	char *luapath="./script/lua/lua.lua";
	luaL_dofile(L, luapath);

	double sinv = 30*3.1415926/180.0;
	lua_getglobal(L, "SIN");
	lua_pushnumber(L, sinv);
	if (0 != lua_pcall(L, 1, 1, 0))
	{
		printf("cpp call lua function failed\n");
	}
	printf("sin(%f)=%f\n", sinv, lua_tonumber(L, -1));
	lua_pop(L, 1);


	lua_getglobal(L, "COS");
	lua_pushnumber(L, 0.5);
	if (0 != lua_pcall(L, 1, 1, 0))
	{
		printf("cpp call lua function failed\n");
	}
	printf("cos(0.5)=%f\n", lua_tonumber(L, -1));
	lua_pop(L, 1);




	//压栈后设置一个lua可调用的全局函数名
	lua_pushcfunction(L, ShowMessage);
	lua_setglobal(L, "showmessage");
	//c调用lua
	lua_getglobal(L, "SHOWMESSAGE");
	lua_pcall(L, 0, 0, 0);
	printf("get the showmessage pushed value %f \n", lua_tonumber(L, -1));

	lua_close(L);

}


--region lua.lua
--Date
--此文件由[BabeLua]插件自动生成

function COS(a)
print("called COS in lua script")
--lua调用c/c++
return DY_MATH.cos(a)
end


function SIN(a)
print("called SIN in lua script")
return DY_MATH.sin(a)
end


function SHOWMESSAGE()
showmessage()
end
--endregion