首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Lua5.2嵌入C++

问Lua5.2嵌入C++
EN

Stack Overflow用户
提问于 2013-10-11 09:51:47
回答 1查看 1.7K关注 0票数 3

我第一次尝试在C++中嵌入Lua。我已经搜索了2天了,但是大多数的网络tutos都使用lua5.1,这与lua5.2不兼容。因此,我阅读了一些lua文档、示例源代码,最后得到了以下内容:

main.cpp:

代码语言:javascript
复制
#include "luainc.h"
#include <iostream>

int main(){
    int iErr = 0;
    lua_State *lua = luaL_newstate ();  // Open Lua
    luaopen_io (lua);    // Load io library

    if ((iErr = luaL_loadfile (lua, "hw.lua")) == 0)
    {
       std::cout<<"step1"<<std::endl;

       if ((iErr = lua_pcall (lua, 0, LUA_MULTRET, 0)) == 0)
       { 
          std::cout<<"step2"<<std::endl;

          lua_getglobal (lua, "helloWorld");    // Push the function name onto the stack

            if (lua_type(lua, lua_gettop(lua)) == LUA_TNIL) {
                // if the global variable does not exist then we will bail out with an error.
                std::cout<<"global variable not found : helloworld"<<std::endl;

                /* error so we will just clear the Lua virtual stack and then return
if we do not clear the Lua stack, we leave garbage that will cause problems with later 
function calls from the application. we do this rather than use lua_error() because this function
is called from the application and not through Lua. */

                lua_settop (lua, 0);
                return -1;
            }         

          // Function is located in the Global Table
          /* lua_gettable (lua, LUA_GLOBALSINDEX);  */ //lua5.1
          lua_pcall (lua, 0, 0, 0);
       }
    }

    lua_close (lua);

    return 0;
}

hw.lua:

代码语言:javascript
复制
-- Lua Hello World (hw.lua)
function helloWorld ()
   io.write ("hello World")
end

luainc.h:

代码语言:javascript
复制
#ifndef __LUA_INC_H__
#define __LUA_INC_H__

extern "C"
{
   #include </home/renardc/Documents/Programmation/Lua_CPP/lua-5.2.2/src/lua.h>
   #include </home/renardc/Documents/Programmation/Lua_CPP/lua-5.2.2/src/lauxlib.h>
   #include </home/renardc/Documents/Programmation/Lua_CPP/lua-5.2.2/src/lualib.h>
}

#endif // __LUA_INC_H__

我没有错误,输出是:

代码语言:javascript
复制
step1
step2

这意味着我的"helloworld“函数已经找到了。但是由于我无法在输出中看到"Hello“,所以我怀疑函数没有被调用。我做错什么了?

我就是这样编译我的程序的:

代码语言:javascript
复制
g++ main.cpp -L/usr/local/include -I/usr/local/include -llua
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-11 10:51:49

首先,为什么不是#include "lua.hpp",它与Lua一起提供,并且主要做luainc.h所做的事情?

您的代码有两个问题:

  1. 当luadL_loadfile失败时,不会发出任何错误消息。
  2. 使用lua_pcall调用helloWorld,但不测试其返回值。

当您将lua_pcall更改为lua_call时,将得到以下错误消息:

尝试索引全局“io”(一个零值)

这意味着您在调用io之后忘记设置全局luaopen_io。只要添加lua_setglobal(lua,"io"),它就能工作。与Lua5.1不同,Lua5.2在打开库时不会自动设置全局值,除非库本身这样做,这是不鼓励的。

您最好调用luaL_openlibs来打开所有标准的Lua库,而不会有任何意外。

您可以使用luaL_dofile而不是luaL_loadfile来保存第一个lua_pcall。您仍然需要检查返回值。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19315192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档