C++与Lua5.3.2的相互调用
2016-04-28 16:51
351 查看
重Lua官网下载最新的Lua5.3.2解压后把src文件下的所有文件(Lua.c,Luac.c除外)复制到项目的目录下,并添加到项目中,
创建一个Lua脚本文件
C++文件如下
创建一个Lua脚本文件
--region *.lua --Date --此文件由[BabeLua]插件自动生成 print("lua script func.lua have been load ") avg, sum = average(10, 20, 30, 40, 50) print("The average is ", avg) print("The sum is ", sum) function add(x,y) return x+y+x*y end --endregion
C++文件如下
#include <iostream> #include <stdio.h> extern "C" { //#include "lprefix.h" #include "lua.h" #include "lauxlib.h" #include "lualib.h" } using namespace std; lua_State* L; static int average(lua_State *L) { //返回栈中元素的个数 int n = lua_gettop(L); double sum = 0; int i; for (i = 1; i <= n; i++) { if (!lua_isnumber(L, i)) { lua_pushstring(L, "Incorrect argument to 'average'"); lua_error(L); } sum += lua_tonumber(L, i); } /* push the average */ lua_pushnumber(L, sum / n); /* push the sum */ lua_pushnumber(L, sum); /* return the number of results */ return 2; } void main() { //cout << "Hello CML" << endl; /* 初始化 Lua */ L = luaL_newstate(); /* 载入Lua基本库 */ luaL_openlibs(L); /* register our function */ lua_register(L, "average", average); /* 运行脚本 */ luaL_dofile(L, "e://lua1.lua"); lua_getglobal(L, "avg"); int avg = lua_tointeger(L, -1); lua_pop(L, 1); lua_getglobal(L, "sum"); int sum = lua_tointeger(L, -1); lua_getglobal(L, "add"); lua_pushinteger(L, 10); lua_pushinteger(L, 20); lua_pcall(L, 2, 1, 0); printf("lua add function return val is %d \n", lua_tointeger(L, -1)); /* 清除Lua */ lua_close(L); /* 暂停 */ printf("Press enter to exit…"); getchar(); }
相关文章推荐
- Lua 中的string库(字符串函数库)总结
- RobotFrameWork(四)变量运算与Evaluate
- C++调用lua简单的例子
- Lua从入门到放弃--协同程序
- Lua简明教程
- Lua学习(五)函数进阶篇
- Lua学习(四)函数
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- Lua学习(三)语句
- Lua 15 分钟快速入门(Learn Lua in 15 Minutes)
- lua和php的基本数据类型
- lua学习二
- lua学习三
- Lua从入门到放弃--垃圾回收
- LuaBridge 中C++类和继承示例
- Lua学习(二)表达式
- Lua学习(一)类型和值
- LuaInterface的反射调用机制研究
- lua math库