LuaBind:无法访问全局变量。

我有一个 C++ 类,我想通过一个全局变量在 lua 脚本中访问它,但当我试图使用它时,我会得到以下错误:

terminate called after throwing an instance of 'luabind::error'
  what():  lua runtime error
baz.lua:3: attempt to index global 'foo' (a nil value)Aborted (core dumped)

我的 Lua 脚本 (baz.lua) 如下所示:

-- baz.lua
frames = 0
bar = foo:createBar()

function baz()
  frames = frames + 1

  bar:setText("frame: " .. frames)
end

我做了一个简单和短的 (尽可能短) main.cpp 来重现这个问题:

#include <memory>
#include <iostream>

extern "C" {
  #include "lua.h"
  #include "lualib.h"
  #include "lauxlib.h"
}

#include <boost/ref.hpp>
#include <luabind/luabind.hpp>

class bar
{
public:
  static void init(lua_State *L)
  {
    using luabind::module;
    using luabind::class_;

    module(L)
    [
      class_<bar>("bar")
        .def("setText", &bar::setText)
    ];
  }

  void setText(const std::string &text)
  {
    std::cout << text << std::endl;
  }
};

class foo
{
public:
  foo() :
    L(luaL_newstate())
  {
    int ret = luaL_dofile(L, "baz.lua");
    if (ret != 0) {
      std::cout << lua_tostring(L, -1);
    }

    luabind::open(L);

    using luabind::module;
    using luabind::class_;

    module(L)
    [
      class_<foo>("bar")
        .def("createBar", &foo::createBar)
    ];

    bar::init(L);
    luabind::globals(L)["foo"] = boost::ref(*this);
  }

  boost::reference_wrapper<bar> createBar()
  {
    auto b = std::make_shared<bar>();
    bars_.push_back(b);

    return boost::ref(*b.get());
  }

  void baz()
  {
    luabind::call_function<void>(L, "baz");
  }

private:
  lua_State *L;
  std::vector<std::shared_ptr<bar>> bars_;
};

int main()
{
  foo f;

  while (true) {
    f.baz();
  }
}

这是编译的:

g++ -std=c++11 -llua -lluabind main.cpp

我发现如果我把 bar = foo:createBar() 放到 baz() 函数中,那么它就不会出错了,所以我假设我没有正确地初始化全局名称空间中的全局变量?我是否遗漏了需要调用的 luabind 函数,因此才能做到这一点?还是根本不可能...谢谢!

点赞
用户2198692
用户2198692

在注册全局变量之前,您正在运行baz.lua。将dofile命令放在注册绑定之后。

顺序如下:

  • 在C ++中调用foo的构造函数,
  • 创建Lua状态
  • 运行lua.baz
  • 注册绑定,
  • 然后在C ++中调用f.baz。
2014-03-06 07:31:54