c++ 与 lua函数互调
来源:互联网 发布:剧本写作软件 编辑:程序博客网 时间:2024/06/06 16:41
// TestLua.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <string>#include <iostream>extern "C"{#include "lua.h"#include "lualib.h"#include "lauxlib.h"};using namespace std;lua_State* L;//接口方法static int Lua_Average(lua_State* lua){int n = lua_gettop(lua); //返回战中元素的个数float sum = 0;int i = 1;for(i; i <= n; i++){if(!lua_isnumber(lua, i)){lua_pushstring(L,"**** there has a error, argument has not number");lua_error(lua);}sum += lua_tonumber(lua, i);}lua_pushnumber(lua, sum/n); //将数值返回lualua_pushnumber(lua, sum);return 2;}int _tmain(int argc, _TCHAR* argv[]){//初始化luaL = luaL_newstate();luaL_openlibs(L);//函数注册lua_register(L,"Average", Lua_Average);//加载lua脚本, 脚本放在工程目录下luaL_loadfile(L, "testA.lua");int dwError = lua_pcall(L, 0 ,LUA_MULTRET,0);if(dwError != 0){cout<<lua_tostring(L,-1);lua_close(L);return 1;}lua_getglobal(L, "avg");cout<<"avg is "<<lua_tostring(L, -1) << endl;lua_pop(L, 1);lua_getglobal(L,"sum");cout<<"sum = "<<lua_tointeger(L,-1)<<endl;lua_pop(L, 1);//调用 lua中的函数int a = 10;int b = 11;lua_getglobal(L,"SumFunc");lua_pushinteger(L,a);lua_pushinteger(L,b);int dwRet = lua_pcall(L,2,1,0);if(dwRet != 0){cout<<lua_tostring(L, -1);lua_pop(L,1);return 0;}printf("sum: %d + %d = %ld\n", a,b,lua_tointeger(L,-1));lua_pop(L,-1);//调用结束,清除Lua lua_close(L);return 0;}
Lua 脚本
function SumFunc( a, b)<span style="white-space:pre"></span>return a + b;endavg, sum = Average(10, 20, 30, 40, 50)print("The average is ", avg)print("The sum is ", sum)
注:
1. c++中的函数注册最好是在lua脚本加载之前完成注册,否则lua 文件如果在加载后就调用c++中的函数时会报错
0 0
- C调Lua函数
- lua 与 c++ 函数互调
- c++ 与 lua函数互调
- C/C++与Lua互调案例
- Lua与C/C++交互函数问题
- Lua与C——调用Lua函数(三)
- [lua]C调用lua函数
- 注册C函数与类成员函数到lua
- 【Lua】Lua与C交互
- C C++调 用LUA的函数
- Lua调用C函数
- lua 调用c函数
- Lua调用C函数
- lua调用c函数
- Lua调用C函数
- lua调用C函数
- lua调用C函数
- lua调用C函数
- 拉黑 CNNIC 证书之后如何访问使用其证书的网站
- 整数划分如,对于正整数n=6,可以分划为:6 5+1
- JavaScript语言精粹【语法、对象、函数】
- 正在运行的android程序,按home键之后退回到桌面,在次点击程序图标避免再次重新启动程序解决办法
- javax.servlet.Filter
- c++ 与 lua函数互调
- 常见Oracle SQL易出错点
- 03-树3. Tree Traversals Again
- 基于B-树和B+树的使用:数据搜索和数据库索引的详细介绍
- javascript Date扩展(日期格式化)
- JVM原理和优化
- GDI与DirectDraw之间的区别
- Android手机软键盘遮盖输入框之重新布局详解
- 【VB.Net机房重构】--简述配置文件