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

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

输出结果为:

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

Lua 语言 15 分钟快速入门

Lua程序设计(第2版)中文 PDF

Lua程序设计(第二版)阅读笔记

NetBSD 将支持用 Lua 脚本开发内核组件

CentOS 编译安装 Lua LuaSocket

Lua 的详细介绍:请点这里
Lua 的下载地址:请点这里

本文永久更新链接地址:

相关内容