docs.rst.svn-base
来自「本人找过多个在linux下c++的lua5.1封装库,但很少.luabind已经」· SVN-BASE 代码 · 共 2,173 行 · 第 1/5 页
SVN-BASE
2,173 行
+++++++++ luabind+++++++++:Author: Daniel Wallin, Arvid Norberg:Copyright: Copyright Daniel Wallin, Arvid Norberg 2003.:Date: $Date$:Revision: $Revision$:License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE... _MIT license: http://www.opensource.org/licenses/mit-license.php.. _Boost: http://www.boost.orgNote: This library is currently in public beta phase. This documentationshould be considered beta as well. Please report any grammatical corrections/spelling corrections... contents:: :depth: 2 :backlinks: none.. section-numbering::Introduction============Luabind is a library that helps you create bindings between C++ and Lua. It hasthe ability to expose functions and classes, written in C++, to Lua. It willalso supply the functionality to define classes in Lua and let them derive fromother Lua classes or C++ classes. Lua classes can override virtual functionsfrom their C++ base classes. It is written towards Lua 5.0, and does not workwith Lua 4.It is implemented utilizing template meta programming. That means that youdon't need an extra preprocess pass to compile your project (it is done by thecompiler). It also means you don't (usually) have to know the exact signature of each function you register, since the library will generate code depending on the compile-time type of the function (which includes the signature). The main drawback of this approach is that the compilation time will increase for the file that does the registration, it is therefore recommended that you register everything in the same cpp-file.Luabind is released under the terms of the `MIT license`_.We are very interested in hearing about projects that use luabind, please letus know about your project.The main channel for help and feedback is the `luabind mailing list`_.There's also an IRC channel ``#luabind`` on irc.freenode.net... _`luabind mailing list`: https://lists.sourceforge.net/lists/listinfo/luabind-userFeatures========Luabind supports: - Overloaded free functions - C++ classes in Lua - Overloaded member functions - Operators - Properties - Enums - Lua functions in C++ - Lua classes in C++ - Lua classes (single inheritance) - Derives from Lua or C++ classes - Override virtual functions from C++ classes - Implicit casts between registered types - Best match signature matching - Return value policies and parameter policies Portability===========Luabind has been tested to work on the following compilers: - Visual Studio 7.1 - Visual Studio 7.0 - Visual Studio 6.0 (sp 5) - Intel C++ 6.0 (Windows) - GCC 2.95.3 (cygwin) - GCC 3.0.4 (Debian/Linux) - GCC 3.1 (SunOS 5.8) - GCC 3.2 (cygwin) - GCC 3.3.1 (cygwin) - GCC 3.3 (Apple, MacOS X) - GCC 4.0 (Apple, MacOS X)It has been confirmed not to work with: - GCC 2.95.2 (SunOS 5.8) Metrowerks 8.3 (Windows) compiles but fails the const-test. This means that const member functions are treated as non-const member functions.If you have tried luabind with a compiler not listed here, let us know your result with it.Building luabind================To keep down the compilation-time luabind is built as a library. This means youhave to either build it and link against it, or include its source files inyour project. You also have to make sure the luabind directory is somewhere inyour compiler's include path. It requires `Boost`_ 1.32.0 or 1.33.0 to beinstalled (only boost headers). It also requires that Lua is installed.The official way of building luabind is with `Boost.Build V2`_. To properly buildluabind with Boost.Build you need to set two environment variables:BOOST_ROOT Point this to your Boost installation.LUA_PATH Point this to your Lua directory. The build system will assume that the include and library files are located in ``$(LUA_PATH)/include/`` and ``$(LUA_PATH)/lib/.``. If this environment variable is not defined, the Jamfile will try to invoke ``pkg-config`` in order to find lua. It will look for lua 5.1 (``lua5.1`` as the package is called on debian systems).For backward compatibility, there is also a makefile in the root-directory thatwill build the library and the test programs. If you are using a UNIX-system (orcygwin) they will make it easy to build luabind as a static library. If you areusing Visual Studio it may be easier to include the files in the src directoryin your project.When building luabind you have several options that may streamline the libraryto better suit your needs. It is extremely important that your application hasthe same settings as the library was built with. The available options arefound in the `Build options`_ section.If you want to change the settings to differ from the default, it's recommendedthat you define the settings on the command line of all your files (in theproject settings in visual studio)... _`Boost.Build V2`: http://www.boost.org/tools/build/v2/index_v2.htmlBasic usage===========To use luabind, you must include ``lua.h`` and luabind's main header file:: extern "C" { #include "lua.h" } #include <luabind/luabind.hpp>This includes support for both registering classes and functions. If you justwant to have support for functions or classes you can include``luabind/function.hpp`` and ``luabind/class.hpp`` separately:: #include <luabind/function.hpp> #include <luabind/class.hpp>The first thing you need to do is to call ``luabind::open(lua_State*)`` whichwill register the functions to create classes from Lua, and initialize somestate-global structures used by luabind. If you don't call this function youwill hit asserts later in the library. There is no corresponding close functionbecause once a class has been registered in Lua, there really isn't any goodway to remove it. Partly because any remaining instances of that class relieson the class being there. Everything will be cleaned up when the state isclosed though... Isn't this wrong? Don't we include lua.h using lua_include.hpp ?Luabind's headers will never include ``lua.h`` directly, but through``<luabind/lua_include.hpp>``. If you for some reason need to include anotherLua header, you can modify this file.Hello world-----------:: #include <iostream> #include <luabind/luabind.hpp> void greet() { std::cout << "hello world!\n"; } extern "C" int init(lua_State* L) { using namespace luabind; open(L); module(L) [ def("greet", &greet) ]; return 0; }:: Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio > loadlib('hello_world.dll', 'init')() > greet() Hello world! >Scopes======Everything that gets registered in Lua is registered in a namespace (Luatables) or in the global scope (called module). All registrations must besurrounded by its scope. To define a module, the ``luabind::module`` class isused. It is used like this:: module(L) [ // declarations ];This will register all declared functions or classes in the global namespace inLua. If you want to have a namespace for your module (like the standardlibraries) you can give a name to the constructor, like this:: module(L, "my_library") [ // declarations ];Here all declarations will be put in the my_library table.If you want nested namespace's you can use the ``luabind::namespace_`` class. Itworks exactly as ``luabind::module`` except that it doesn't take a lua_State*in it's constructor. An example of its usage could look like this:: module(L, "my_library") [ // declarations namespace_("detail") [ // library-private declarations ] ];As you might have figured out, the following declarations are equivalent:: module(L) [ namespace_("my_library") [ // declarations ] ];:: module(L, "my_library") [ // declarations ];Each declaration must be separated by a comma, like this:: module(L) [ def("f", &f), def("g", &g), class_<A>("A") .def(constructor<int, int>), def("h", &h) ];More about the actual declarations in the `Binding functions to Lua`_ and`Binding classes to Lua`_ sections.A word of caution, if you are in really bad need for performance, putting yourfunctions in tables will increase the lookup time.Binding functions to Lua========================To bind functions to Lua you use the function ``luabind::def()``. It has thefollowing synopsis:: template<class F, class policies> void def(const char* name, F f, const Policies&);- name is the name the function will have within Lua. - F is the function pointer you want to register. - The Policies parameter is used to describe how parameters and return values are treated by the function, this is an optional parameter. More on this in the `policies`_ section.An example usage could be if you want to register the function ``floatstd::sin(float)``:: module(L) [ def("sin", &std::sin) ];Overloaded functions--------------------If you have more than one function with the same name, and want to registerthem in Lua, you have to explicitly give the signature. This is to let C++ knowwhich function you refer to. For example, if you have two functions, ``intf(const char*)`` and ``void f(int)``. :: module(L) [ def("f", (int(*)(const char*)) &f), def("f", (void(*)(int)) &f) ];Signature matching------------------luabind will generate code that checks the Lua stack to see if the values therecan match your functions' signatures. It will handle implicit typecasts betweenderived classes, and it will prefer matches with the least number of implicitcasts. In a function call, if the function is overloaded and there's nooverload that match the parameters better than the other, you have anambiguity. This will spawn a run-time error, stating that the function call isambiguous. A simple example of this is to register one function that takes anint and one that takes a float. Since Lua doesn't distinguish between floats andintegers, both will always match.Since all overloads are tested, it will always find the best match (not thefirst match). This also means that it can handle situations where the onlydifference in the signature is that one member function is const and the otherisn't. .. sidebar:: Ownership transfer To correctly handle ownership transfer, create_a() would need an adopt return value policy. More on this in the `Policies`_ section.For example, if the following function and class is registered::: struct A { void f(); void f() const; }; const A* create_a(); struct B: A {}; struct C: B {}; void g(A*); void g(B*);And the following Lua code is executed:: a1 = create_a() a1:f() -- the const version is called a2 = A() a2:f() -- the non-const version is called a = A() b = B() c = C() g(a) -- calls g(A*) g(b) -- calls g(B*) g(c) -- calls g(B*)Calling Lua functions---------------------To call a Lua function, you can either use ``call_function()`` oran ``object``.:: template<class Ret> Ret call_function(lua_State* L, const char* name, ...) template<class Ret> Ret call_function(object const& obj, ...)There are two overloads of the ``call_function`` function, one that callsa function given its name, and one that takes an object that should be a Luavalue that can be called as a function.The overload that takes a name can only call global Lua functions. The ...represents a variable number of parameters that are sent to the Luafunction. This function call may throw ``luabind::error`` if the functioncall fails.The return value isn't actually Ret (the template parameter), but a proxyobject that will do the function call. This enables you to give policies to thecall. You do this with the operator[]. You give the policies within thebrackets, like this:: int ret = call_function<int>( L , "a_lua_function" , new complex_class() )[ adopt(_1) ];If you want to pass a parameter as a reference, you have to wrap it with the
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?