【问题标题】:luabind: cannot access global variableluabind:无法访问全局变量
【发布时间】:2014-04-08 14:59:35
【问题描述】:

我有一个 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 函数?或者这根本不可能……

谢谢!

【问题讨论】:

    标签: c++ lua luabind


    【解决方案1】:

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

    顺序如下:

    • 您在 C++ 中调用 foo 的构造函数,它
    • 创建一个 Lua 状态
    • 运行lua.baz
    • 注册您的绑定
    • 然后在 c++ 中调用 f.baz。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 2016-11-12
      • 2019-03-29
      • 2012-03-06
      相关资源
      最近更新 更多