2014-03-06 3 views
1

나는 내가 다음과 같은 오류 얻을 그것을 사용하려고하지만 내가 전역 변수를 통해 루아 스크립트에 대한 액세스 권한을 부여하려는 ++ 클래스는 C를 :luabind : 전역 변수를 액세스 할 수 없습니다

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) 

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

function baz() 
    frames = frames + 1 

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

그리고 나는이 문제를 재현 간단하고 (물론 내가 할 수있는 등의) 짧은 MAIN.CPP 만든거야 : 내 루아 스크립트 (baz.lua)은 다음과 같습니다

#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 

내가 발견 한 나는 baz() 기능에 bar = foo:createBar()를 넣어 경우 다음 오류하지 않는, 그래서 내가 제대로 글로벌 네임 스페이스의 전역을 초기화하는 아니에요 가정 ? 내가 이것을 할 수 있기 전에 호출해야 할 루아 바인드 함수가 빠졌습니까? 아니면 전혀 불가능합니다 ...

고마워요!

답변

2

모든 글로벌을 등록하기 전에 baz.lua을 실행 중입니다. 바인딩을 등록한 후 dofile 명령을 입력하십시오.

순서는 다음과 같다 :

  • 당신은
  • 는 루아 상태를
  • 실행 lua.baz
  • 등록하여 바인딩 당신이 전화를 C++에서 다음
  • 를 생성 ++ C에서 foo는의 생성자를 호출 f.baz.
+0

위대한! 좋은 간단하고, 감사합니다 :) –