2010-06-30 64 views
4

我正在嘗試將腳本機制集成到我現有的項目中。但是我無法理解如何將對象傳遞給luabind。如何在C++中用luabind傳遞和更新對象

例如,我有一個實體類,我想在lua文件中更新它們。

#include <stdio.h> 
#include <ctime> 
#include <iostream> 
#include <string> 
#include <list> 
using namespace std; 

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

#include <luabind/luabind.hpp> 


class Entity 
{ 
    public: 

     Entity(){} 
     ~Entity(){} 

     void setSpeed(double adSpeed){m_dSpeed = adSpeed;} 
     void setPosition(double adPosition){m_dPosition = adPosition;} 

     double getSpeed(){return m_dSpeed;} 
     double getPosition(){return m_dPosition;} 

    private: 

     double m_dSpeed; 
     double m_dPosition; 

}; 

int main() { 


    // Create a new lua state 
    lua_State *myLuaState = lua_open(); 
    // Connect LuaBind to this lua state 
    luabind::open(myLuaState); 

    // Export our class with LuaBind 
    luabind::module(myLuaState) [ 
     luabind::class_<Entity>("Entity") 
      .def(luabind::constructor<void>()) 
      .property("m_dSpeed", &Entity::getSpeed, &Entity::setSpeed) 
      .property("m_dPosition", &Entity::getPosition, &Entity::setPosition) 
    ]; 



    luabind::object table = luabind::newtable(myLuaState); 


    Entity* entity1 = new Entity; 

    table["Entity1"] = entity1; 

    //How to pass entity object to lua 

    luabind::luaL_dofile(myLuaState, "UpdatePosition.lua"); 

    lua_close(myLuaState); 

    return 1; 
} 

這裏是我想學的code.What是通過實體對象和時間價值,Lua和利用他們的速度和增量時間更新自己的位置。

回答

4
luabind::globals(myLuaState)["entities"] = table; 

基本上,luabind::globals(lua)返回_G LUA表,您可以操控如常。

+0

當我將此行添加到code.Code因爲未處理的異常而在運行時崩潰。 – Qubeuc 2010-07-01 07:59:13

+0

@Qubeuc:什麼是例外? – sbk 2010-07-01 09:09:05