docs.rst.svn-base

来自「本人找过多个在linux下c++的lua5.1封装库,但很少.luabind已经」· SVN-BASE 代码 · 共 2,173 行 · 第 1/5 页

SVN-BASE
2,173
字号
pointer must be a raw pointer, it is also needed to allow the smart_pointer ->raw_pointer conversion from Lua to C++. They look like this::    namespace luabind {        template<class T>        T* get_pointer(boost::shared_ptr<T>& p)         {            return p.get();         }        template<class A>        boost::shared_ptr<const A>*         get_const_holder(boost::shared_ptr<A>*)        {            return 0;        }    }The second function will only be used to get a compile time mappingof ``boost::shared_ptr<A>`` to its const version,``boost::shared_ptr<const A>``. It will never be called, so thereturn value doesn't matter (only the return type).The conversion that works are (given that B is a base class of A):.. topic:: From Lua to C++    ========================= ========================    Source                    Target    ========================= ========================    ``holder_type<A>``        ``A*``    ``holder_type<A>``        ``B*``    ``holder_type<A>``        ``A const*``    ``holder_type<A>``        ``B const*``    ``holder_type<A>``        ``holder_type<A>``    ``holder_type<A>``        ``holder_type<A const>``    ``holder_type<A const>``  ``A const*``    ``holder_type<A const>``  ``B const*``    ``holder_type<A const>``  ``holder_type<A const>``    ========================= ========================.. topic:: From C++ to Lua    =============================== ========================    Source                          Target    =============================== ========================    ``holder_type<A>``              ``holder_type<A>``    ``holder_type<A const>``        ``holder_type<A const>``    ``holder_type<A> const&``       ``holder_type<A>``    ``holder_type<A const> const&`` ``holder_type<A const>``    =============================== ========================When using a holder type, it can be useful to know if the pointer is valid(i.e. not null). For example when using std::auto_ptr, the holder will beinvalidated when passed as a parameter to a function. For this purpose thereis a member of all object instances in luabind: ``__ok``. ::    struct X {};    void f(std::auto_ptr<X>);    module(L)    [        class_<X, std::auto_ptr<X> >("X")            .def(constructor<>()),        def("f", &f)    ];::        Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio    > a = X()    > f(a)    > print a.__ok    falseWhen registering a hierarchy of classes, where all instances are to be heldby a smart pointer, all the classes should have the baseclass' holder type.Like this:.. parsed-literal::        module(L)        [            class_<base, boost::shared_ptr<base> >("base")                .def(constructor<>()),            class_<derived, base, **boost::shared_ptr<base>** >("base")                .def(constructor<>())        ];Internally, luabind will do the necessary conversions on the raw pointers, whichare first extracted from the holder type.Splitting class registrations-----------------------------In some situations it may be desirable to split a registration of a classacross different compilation units. Partly to save rebuild time when changingin one part of the binding, and in some cases compiler limits may force youto split it. To do this is very simple. Consider the following sample code::    void register_part1(class_<X>& x)    {        x.def(/*...*/);    }    void register_part2(class_<X>& x)    {        x.def(/*...*/);    }    void register_(lua_State* L)    {        class_<X> x("x");        register_part1(x);        register_part2(x);        module(L) [ x ];    }Here, the class ``X`` is registered in two steps. The two functions``register_part1`` and ``register_part2`` may be put in separate compilationunits.To separate the module registration and the classes to be registered, see`Splitting up the registration`_.Object======Since functions have to be able to take Lua values (of variable type) we need awrapper around them. This wrapper is called ``luabind::object``. If thefunction you register takes an object, it will match any Lua value. To use it,you need to include ``<luabind/object.hpp>``... topic:: Synopsis    .. parsed-literal::        class object        {        public:            template<class T>            object(lua_State\*, T const& value);            object(from_stack const&);            object(object const&);            object();            ~object();            lua_State\* interpreter() const;            void push() const;            bool is_valid() const;            operator *safe_bool_type* () const;            template<class Key>            *implementation-defined* operator[](Key const&);            template<class T>            object& operator=(T const&);            object& operator=(object const&);            bool operator==(object const&) const;            bool operator<(object const&) const;            bool operator<=(object const&) const;            bool operator>(object const&) const;            bool operator>=(object const&) const;            bool operator!=(object const&) const;            template <class T>            *implementation-defined* operator[](T const& key) const            void swap(object&);            *implementation-defined* operator()();            template<class A0>            *implementation-defined* operator()(A0 const& a0);            template<class A0, class A1>            *implementation-defined* operator()(A0 const& a0, A1 const& a1);            /\* ... \*/        };When you have a Lua object, you can assign it a new value with the assignmentoperator (=). When you do this, the ``default_policy`` will be used to make theconversion from C++ value to Lua. If your ``luabind::object`` is a table youcan access its members through the operator[] or the Iterators_. The valuereturned from the operator[] is a proxy object that can be used both forreading and writing values into the table (using operator=).Note that it is impossible to know if a Lua value is indexable or not(``lua_gettable`` doesn't fail, it succeeds or crashes). This means that ifyou're trying to index something that cannot be indexed, you're on your own.Lua will call its ``panic()`` function. See `lua panic`_.There are also free functions that can be used for indexing the table, see`Related functions`_.The constructor that takes a ``from_stack`` object is used when you want toinitialize the object with a value from the lua stack. The ``from_stack``type has the following constructor::	 from_stack(lua_State* L, int index);The index is an ordinary lua stack index, negative values are indexed from thetop of the stack. You use it like this::	 object o(from_stack(L, -1));This will create the object ``o`` and copy the value from the top of the lua stack.The ``interpreter()`` function returns the Lua state where this object is stored.If you want to manipulate the object with Lua functions directly you can pushit onto the Lua stack by calling ``push()``.The operator== will call lua_equal() on the operands and return its result.The ``is_valid()`` function tells you whether the object has been initializedor not. When created with its default constructor, objects are invalid. To makean object valid, you can assign it a value. If you want to invalidate an objectyou can simply assign it an invalid object.The ``operator safe_bool_type()`` is equivalent to ``is_valid()``. This meansthat these snippets are equivalent::    object o;    // ...    if (o)    {        // ...    }    ...    object o;    // ...    if (o.is_valid())    {        // ...    }The application operator will call the value as if it was a function. You cangive it any number of parameters (currently the ``default_policy`` will be usedfor the conversion). The returned object refers to the return value (currentlyonly one return value is supported). This operator may throw ``luabind::error``if the function call fails. If you want to specify policies to your functioncall, you can use index-operator (operator[]) on the function call, and givethe policies within the [ and ]. Like this::    my_function_object(        2      , 8      , new my_complex_structure(6)    ) [ adopt(_3) ];This tells luabind to make Lua adopt the ownership and responsibility for thepointer passed in to the lua-function.It's important that all instances of object have been destructed by the timethe Lua state is closed. The object will keep a pointer to the lua state andrelease its Lua object in its destructor.Here's an example of how a function can use a table::    void my_function(object const& table)    {        if (type(table) == LUA_TTABLE)        {            table["time"] = std::clock();            table["name"] = std::rand() < 500 ? "unusual" : "usual";            std::cout << object_cast<std::string>(table[5]) << "\n";        }    }If you take a ``luabind::object`` as a parameter to a function, any Lua valuewill match that parameter. That's why we have to make sure it's a table beforewe index into it.::    std::ostream& operator<<(std::ostream&, object const&);There's a stream operator that makes it possible to print objects or use``boost::lexical_cast`` to convert it to a string. This will use lua's stringconversion function. So if you convert a C++ object with a ``tostring``operator, the stream operator for that type will be used.Iterators---------There are two kinds of iterators. The normal iterator that will use the metamethodof the object (if there is any) when the value is retrieved. This iterator is simplycalled ``luabind::iterator``. The other iterator is called ``luabind::raw_iterator``and will bypass the metamethod and give the true contents of the table. They haveidentical interfaces, which implements the ForwardIterator_ concept. Apart fromthe members of standard iterators, they have the following members and constructors:.. _ForwardIterator: http://www.sgi.com/tech/stl/ForwardIterator.html.. parsed-literal::    class iterator    {        iterator();        iterator(object const&);        object key() const;        *standard iterator members*    };The constructor that takes a ``luabind::object`` is actually a template that can beused with object. Passing an object as the parameter to the iterator willconstruct the iterator to refer to the first element in the object.The default constructor will initialize the iterator to the one-past-enditerator. This is used to test for the end of the sequence.The value type of the iterator is an implementation defined proxy type whichsupports the same operations as ``luabind::object``. Which means that in mostcases you can just treat it as an ordinary object. The difference is that anyassignments to this proxy will result in the value being inserted at theiterators position, in the table. The ``key()`` member returns the key used by the iterator when indexing theassociated Lua table.An example using iterators::    for (iterator i(globals(L)["a"]), end; i != end; ++i)    {      *i = 1;    }The iterator named ``end`` will be constructed using the default constructorand hence refer to the end of the sequence. This example will simply iterateover the entries in the global table ``a`` and set all its values to 1.Related functions-----------------There are a couple of functions related to objects and tables.::    int type(object const&);This function will return the lua type index of the given object.i.e. ``LUA_TNIL``, ``LUA_TNUMBER`` etc.::    template<class T, class K>    void settable(object const& o, K const& key, T const& value);    template<class K>    object gettable(object const& o, K const& key);    template<class T, class K>    void rawset(object const& o, K const& key, T const& value);    template<class K>    object rawget(object const& o, K const& key);These functions are used for indexing into tables. ``settable`` and ``gettable``translates into calls to ``lua_settable`` and ``lua_gettable`` respectively. Whichmeans that you could just as well use the index operator of the object.``rawset`` and ``rawget`` will translate into calls to ``lua_rawset`` and``lua_rawget`` respectively. So they will bypass any metamethod and give you thetrue value of the table entry.::    template<class T>    T object_cast<T>(object const&);    template<class T, class Policies>    T object_cast<T>(object const&, Policies);    template<class T>    boost::optional<T> object_cast_nothrow<T>(object const&);    template<class T, class Policies>    boost::optional<T> object_cast_nothrow<T>(object const&, Policies);The ``object_cast`` function casts the value of an object to a C++ value.You can supply a policy to handle the conversion from lua to C++. If the castcannot be made a ``cast_failed`` exception will be thrown. If you havedefined LUABIND_NO_ERROR_CHECKING (see `Build options`_) no checking will occur,and if the cast is invalid the application may very well crash. The nothrowversions will return an uninitialized ``boost::optional<T>`` object, toindicate that the cast could not be performed.The function signatures of all of the above functions are really templatesfor the object parameter, but the intention is that you should only passobjects in there, that's why it's left out of the documentation.::    object globals(lua_State*);    object registry(lua_State*);These functions return the global environment table and the registry table respectively.::  object newtable(lua_State*);This function creates a new table and returns it as an object.Assigning nil-------------To set a table entry to ``nil``, you can use ``luabind::nil``. It will avoidhaving to take the detour by first assigning ``nil`` to an object and thenassign that to the table entry. It will simply result in a ``lua_pushnil()``call, instead of copying an object.Example::  using luabind;  object table = newtable(L);  table["foo"] = "bar";    // now, clear the "foo"-field  table["foo"] = nil;Defining classes in Lua=======================In addition to binding C++ functions and classes with Lua, luabind also provide

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?