lua入门之一:c/c++ 调用lua

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 <stdio.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


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;
}

输出结果为:


  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值