C++和Lua的互调

来源:互联网 发布:python 字典是什么 编辑:程序博客网 时间:2024/05/16 18:49
#include <iostream>#include <string>using namespace std;extern "C" {#include "lua.h"#include "lualib.h"#include "lauxlib.h"}//C++调用Luaint CPPUseLua() {    lua_State *L = luaL_newstate();    //加载lua文件    int bRet = luaL_loadfile(L, "test1.lua");    if (bRet) {        cout << bRet << "loadfile fail!" << endl;        return 0;    }    //运行lua文件    bRet = lua_pcall(L, 0, 0, 0);    if (bRet) {        cout << bRet << "pcall fail!" << endl;        return 0;    }    //获取lua中的变量    lua_getglobal(L, "num"); //将num压入栈    int num = lua_tonumber(L, -1); //获取栈顶元素    cout << num << endl;    lua_getglobal(L, "str"); //将str压入栈    string str = lua_tostring(L, -1); //获取栈顶元素    cout << str << endl;    //读取lua的表    lua_getglobal(L, "tbl"); //将tbl压入栈    lua_getfield(L, -1, "name"); //将栈顶table中的name字段压栈    string name = lua_tostring(L, -1); //获取栈顶元素    cout << name << endl;    //调用函数    lua_getglobal(L, "add");    lua_pushnumber(L, 15); //压入参数    lua_pushnumber(L, 25); //压入参数    bRet = lua_pcall(L, 2, 1, 0); //调用栈顶往下的第二个函数,参数个数为2,返回值个数为1    int ret = lua_tonumber(L, -1); //读取返回值    cout << ret << endl;    //关闭L    lua_close(L);}static int average(lua_State *L) {    /* 得到参数个数 */    int n = lua_gettop(L);    double sum = 0;    int i;    /* 循环求参数之和 */    for (i = 1; i <= n; i++)    {        /* 求和 */        sum += lua_tonumber(L, i);    }    /* 压入平均值 */    lua_pushnumber(L, sum / n);    /* 压入和 */    lua_pushnumber(L, sum);    /* 返回返回值的个数 */    return 2;}//Lua调用C++int LuaUseCPP() {    lua_State *L = luaL_newstate();    //注册函数    lua_register(L, "average", average);    //加载文件    int bRet = luaL_loadfile(L, "test2.lua");    if (bRet) {        cout << bRet << "loadfile fail!" << endl;        return 0;    }    //运行lua文件    bRet = lua_pcall(L, 0, 0, 0);    if (bRet) {        cout << bRet << "pcall fail!" << endl;        return 0;    }    cout << lua_gettop(L) << endl;    //测试是否返回正确结果    lua_getglobal(L, "avg");    lua_getglobal(L, "sum");    cout << lua_gettop(L) << endl;    cout << lua_tonumber(L, -1) << endl;    lua_remove(L, -1);    cout << lua_tonumber(L, -1) << endl;    return 0;}int main() {    LuaUseCPP();    return 0;}
原创粉丝点击