设为首页 加入收藏

TOP

Lua入门之一:C/C++ 调用Lua
2014-11-23 20:28:53 来源: 作者: 【 】 浏览:31
Tags:Lua 入门 之一 C/C 调用

Lua和C / C++的数据交互通过栈进行, 操作数据时,首先将数据拷贝到"栈"上,然后获取数据,栈中的每个数据通过索引值进行定位,索引值为正时表示相对于栈底的偏移索引,索引值为负时表示相对于栈顶的偏移索引,索引值以1或 - 1为起始值,因此栈顶索引值永远为 - 1, 栈底索引值永远为1 。 "栈"相当于数据在lua和c / c++之间的中转地。每种数据都有相应的存取接口 。


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


print("lua script func.lua have been load ")



function showinfo()
print("welcome to lua world ")
end


function showstr(str)
print("The string you input is " .. str)
end



function add(x,y)
return x+y;
end
--endregion


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


#include



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



int main(int argc,char ** argv)
{


lua_State * L=NULL;


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


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


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



//获取lua中的showinfo函数
lua_getglobal(L,"showinfo");
//cpp 调用无参数的lua函数,无返回值
lua_pcall(L,0,0,0);
//主动清理堆栈,也可以不调用



const char * pstr="世界如此美好";
lua_getglobal(L,"showstr");
lua_pushstring(L,pstr);
//cpp 调用一个参数的的lua函数,无返回值
lua_pcall(L,1,0,0);


lua_getglobal(L,"add");
//参数从左到右压栈
lua_pushinteger(L,2);
lua_pushinteger(L,3);
lua_pcall(L,2,1,0);
printf("lua add function return val is %d \n",lua_tointeger(L,-1));



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


return 1;
}


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


输出结果为:


Lua入门之一:C/C++ 调用Lua


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C\C++和Lua是如何进行通信的? 下一篇Lua入门之二:C/C++ 调用Lua及多..

评论

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