手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Lua与C++交互初探

[日期:2016-01-01] 来源:Linux社区  作者:Zackzhang [字体:大 中 小]

Lua与C++的交互测试

上面我们已经把需要的环境什么的都配置好了,现在重头戏上场( ̄︶ ̄)

1.我们建一个test.lua文件;

function Communicate(name)

return ("Hello "..name..", I`m in Lua");

end

1.我们调用lua文件的cpp代码

#include "stdafx.h"
#include <iostream> 
#include <string.h> 
using namespace std;

extern "C"
{
#include "lua.h" 
#include "lauxlib.h" 
#include "lualib.h" 
}
void main()
{
    string hello = "This is Zack, I`m in C++";
    cout << hello.c_str() << endl;
    //创建Lua状态 
    lua_State *L = luaL_newstate();
    if (L == NULL)
    {
        return;
    }

    //加载Lua文件 
    int bRet = luaL_loadfile(L, "test.lua");
    if (bRet)
    {
        cout << "load file error" << endl;
        return;
    }

    //运行Lua文件 
    bRet = lua_pcall(L, 0, 0, 0);
    if (bRet)
    {
        cout << "pcall error" << endl;
        return;
    }
                                      //读取函数 
    lua_getglobal(L, "Communicate");        // 获取函数,压入栈中 
    lua_pushstring(L, "Zack");          // 压入参数 
    int iRet = lua_pcall(L, 1, 1, 0);// 调用函数,调用完成以后,会将返回值压入栈中,2表示参数个数,1表示返回结果个数。 
    if (iRet)                      // 调用出错 
    {
        const char *pErrorMsg = lua_tostring(L, -1);
        cout << pErrorMsg << endl;
        lua_close(L);
        return;
    }
    if (lua_isstring(L, -1))        //取值输出 
    {
        string Result = lua_tostring(L, -1);
        cout << Result.c_str() << endl;
    }

    //关闭state 
    lua_close(L);
    system("pause");
    return;
}

结果:

嗯,大功告成。

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

本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-01/126948.htm

linux
相关资讯       Lua 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款