2012-11-10 68 views
0

我在与luabind v0.9.1使用g ++ 4.7(--std=c++11)一个非常微妙的问题和Boost 1.51可在下面的代码被复制:luabind成员函数需要对象作为第一个参数

#include <exception> 
#include <iostream> 
#include <string> 

#include <lua.hpp> 
#include <luabind/luabind.hpp> 

struct TestObject 
{ 
    int x = 0; 

    int increment() 
    { 
     return ++x; 
    } 
}; 

static void luaError(lua_State* stack, const std::string& luaCode, int luaErr) 
{ 
    std::cerr << "Failed with code " << luaErr << ": " << std::endl 
       << "LuaCode: " << luaCode << std::endl 
       << "Message: " << lua_tostring(stack, -1) << std::endl; 
    std::terminate(); 
} 

void luaExec(lua_State* stack, const std::string& luaCode) 
{ 
    if (int excode = luaL_loadbuffer(stack, luaCode.c_str(), luaCode.size(), "luaExec")) 
     luaError(stack, luaCode, excode); 

    if (int excode = lua_pcall(stack, 0, 0, 0)) 
     luaError(stack, luaCode, excode); 
} 

int main() 
{ 
    using namespace luabind; 
    lua_State* L = luaL_newstate(); 
    open(L); 

    module(L) 
    [ 
     class_<TestObject>("TestObject") 
      .def(constructor<>()) 
      .def("increment", &TestObject::increment) 
      .property("x", &TestObject::x) 
    ]; 

    luaExec(L, "obj = TestObject()"); 
    luaExec(L, "obj.increment()"); 
} 

编译在执行此代码的结果:

Failed with code 2: 
LuaCode: obj.increment() 
Message: No matching overload found, candidates: 
int increment(TestObject&) 

但是,如果我改变我对luaExec秒调用luaExec(L, "obj.increment(obj)");,代码执行就好了。这种行为很奇怪。我在这里做错了什么?

回答

0

在与luabind绑定的对象上调用方法需要调用object:method(arg1,arg2,...)语法。这是object.method的语义糖(object,arg1,arg2,...)。这将调用正确的方法(对象的),并传入正确的数据成员(对象的)。请参阅http://lua-users.org/wiki/SimpleLuaClasses了解有关在lua中直接创建类的更多信息:这会通知与luabind绑定的类。

+0

哇,这是一个真正愚蠢的问题,回顾...谢谢:-) –

相关问题