Lua5.2嵌入到C++中。

我第一次尝试在C++中嵌入Lua。我已经搜索了2天,但大多数互联网tutos使用lua5.1,这与lua5.2不兼容。所以我阅读了一些lua文档、示例源代码,最终得到了这个:

main.cpp:

#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:

-- Lua Hello World (hw.lua)
function helloWorld ()
   io.write ("hello World")
end

luainc.h:

#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__

我没有错误,输出是:

step1
step2

这应该意味着我的“helloworld”函数已经被找到。但由于输出中看不到“Hello World”,我怀疑函数没有被调用。我做错了什么?

这是我如何编译我的程序:

g++ main.cpp -L/usr/local/include -I/usr/local/include -llua
点赞
用户107090
用户107090

首先,为什么不使用 #include "lua.hpp" 呢?该文件是 Lua 自带的,并且基本上可以实现你的 luainc.h 的所有功能。

你的代码有两个问题:

  1. luaL_loadfile 失败时,你没有发出任何错误消息。

  2. 你使用 lua_pcall 调用 helloWorld,但没有测试其返回值。

当你将 lua_pcall 改为 lua_call 后,你会收到以下错误消息:

attempt to index global 'io' (a nil value)

这意味着在调用 luaopen_io 后,你忘记了设置全局变量 io。只需添加 lua_setglobal(lua,"io") 即可使其工作。与 Lua 5.1 不同,除非库本身这样做(这是不鼓励的),否则 Lua 5.2 在打开库时不会自动设置全局变量。

为了避免出现意外,你最好使用 luaL_openlibs 打开所有标准的 Lua 库。

你也可以使用 luaL_dofile 替代 luaL_loadfile 并省略第一个 lua_pcall。但是仍需要检查其返回值。

2013-10-11 10:51:49