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

来源:互联网 发布:java 泛型 通配符 编辑:程序博客网 时间:2024/06/04 19:07

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 ")endfunction showstr(str)print("The string you input is " .. str)endfunction add(x,y)return x+y;end--endregion


#include <stdio.h>//lua头文件#ifdef __cplusplusextern "C" {#include "lua.h"  #include <lauxlib.h>   #include <lualib.h>   }  #else#include <lua.h>#include <lualib.h>#include <lauxlib.h>#endifint 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 0
原创粉丝点击