c++ - luabind: cannot access global variable -


i have c++ class want give access in lua script through global variable, when try use following error:

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

my lua script (baz.lua) looks this:

-- baz.lua frames = 0 bar = foo:createbar()  function baz()   frames = frames + 1    bar:settext("frame: " .. frames) end 

and i'm made simple , short (as could) main.cpp recreates problem:

#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();   } } 

this compiled with:

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

i've discovered if put bar = foo:createbar() baz() function doesn't error, assume i'm not initialising globals in global namespace correctly? missing luabind function need call before able this? or not possible @ all...

thanks!

you're running baz.lua before register globals. put dofile command after registering bindings.

the sequence follows:

  • you invoke foo's constructor in c++, which
  • creates lua state
  • runs lua.baz
  • registers bindings
  • then in c++ call f.baz.

Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -