设为首页 加入收藏

TOP

Lua入门之二:C/C++ 调用Lua及多个函数返回值的获取
2014-11-23 20:28:53 来源: 作者: 【 】 浏览:31
Tags:Lua 入门 之二 C/C 调用 多个 函数 返回 获取

当 Lua 调用 C 函数的时候,使用和 C 调用 Lua 相同类型的栈来交互。C 函数从栈中获取她的参数,调用结束后将返回结果放到栈中。为了区分返回结果和栈中的其他的值,每个 C 函数还会返回结果的个数(the function returns (in C) the number of results it is leaving on the stack.)。


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


#include "stdafx.h"


#include



//lua头文件
#ifdef __cplusplus
extern "C" {
#include "lua.h"
#include
#include
}
#else
#include
#include
#include
#endif



int static add(lua_State* L)
{
//获取第一个参数
double x=lua_tonumber(L,1);
double y=lua_tonumber(L,2);
//返回值压栈,压入两个返回值
lua_pushnumber(L,x+y);
lua_pushnumber(L,1000);


//返回值的个数,
return 2;
}



int _tmain(int argc, _TCHAR* argv[])
{




lua_State * L=NULL;


/* 初始化 Lua */
L = lua_open();


/* 载入Lua基本库 */
luaL_openlibs(L);


/* 运行脚本 */
luaL_dofile(L, "./script/func.lua");


//函数入栈
lua_pushcfunction(L,add);
//设置全局函数名
lua_setglobal(L,"Add");
//调用lua函数LUACALLCPP来反调cpp中的add
lua_getglobal(L,"LUACALLCPP");
lua_pushnumber(L,10);
lua_pushnumber(L,34.33);
//两个参数,两个返回值
lua_pcall(L,2,2,0);
//取返回值二
printf("lua call cpp return val is %f \n",lua_tonumber(L,-1));
//取返回值一
printf("lua call cpp return val is %f \n",lua_tonumber(L,-2));




/* 清除Lua */
lua_close(L);


return 0;
}


---------------------------------------


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


print("func.lua hava been loaded")


function LUACALLCPP(x,y)
-- 调用c++中的函数
return Add(x,y)
--print(Add(x,y))
end



--endregion


运行结果:


Lua入门之二:C/C++ 调用Lua及多个函数返回值的获取


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Lua入门之一:C/C++ 调用Lua 下一篇Lua入门之三:Lua调用C/C++库(动..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: