pax_global_header00006660000000000000000000000064136624531030014515gustar00rootroot0000000000000052 comment=a9287d342c70a37b68beca694ee75f2d5c747db4 luabind-1.1.1/000077500000000000000000000000001366245310300131335ustar00rootroot00000000000000luabind-1.1.1/.gitignore000066400000000000000000000001101366245310300151130ustar00rootroot00000000000000bin.v2 bin doc/*.html doc/version.rst nppBackup/ build/ _build/ *.kdev4 luabind-1.1.1/.travis.yml000066400000000000000000000016561366245310300152540ustar00rootroot00000000000000language: cpp os: linux addons: apt: packages: - cmake - libboost-dev env: - C_CXX11=OFF C_LUAV=5.1.5 C_LXX=src - C_CXX11=ON C_LUAV=5.2.4 C_LXX=src - C_CXX11=ON C_LUAV=5.2.4 C_LXX=cxx C_EXTRA="-DLUABIND_CPLUSPLUS_LUA=ON" - C_CXX11=ON C_LUAV=5.3.4 C_LXX=src compiler: - gcc before_install: - mkdir build; cd build - $TRAVIS_BUILD_DIR/get-deps.sh $C_LUAV $C_LXX script: - LUA_DIR=$PWD/lua-$C_LUAV/$C_LXX/ cmake -DLUABIND_BUILD_HEADER_TESTS=ON -DLUABIND_USE_CXX11=$C_CXX11 -DCMAKE_BUILD_TYPE=Debug $C_EXTRA .. - make - CTEST_OUTPUT_ON_FAILURE=1 make test jobs: # clang can only be used in C++98 mode with Travis' old boost version. include: - compiler: clang env: C_CXX11=OFF C_LUAV=5.1.5 C_LXX=src - compiler: clang env: C_CXX11=OFF C_LUAV=5.3.4 C_LXX=cxx C_EXTRA="-DLUABIND_CPLUSPLUS_LUA=ON" luabind-1.1.1/CMakeLists.txt000066400000000000000000000221601366245310300156740ustar00rootroot00000000000000# Build for LuaBind # Ryan Pavlik # http://academic.cleardefinition.com/ # Iowa State University HCI Graduate Program/VRAC cmake_minimum_required(VERSION 2.8.3) set(CMAKE_LEGACY_CYGWIN_WIN32 0) # Remove when CMake >= 2.8.4 is required project(LuaBind) set_property(GLOBAL PROPERTY USE_FOLDERS ON) include(CheckCXXCompilerFlag) set(CPACK_PACKAGE_VERSION_MAJOR "0") set(CPACK_PACKAGE_VERSION_MINOR "9") set(CPACK_PACKAGE_VERSION_PATCH "1") set(CPACK_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}") list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules") if(NOT Boost_FOUND) set(Boost_USE_STATIC_LIBS ON) set(Boost_USE_MULTITHREADED ON) set(Boost_USE_STATIC_RUNTIME OFF) find_package(Boost REQUIRED) endif() if(NOT LUA_FOUND AND NOT LUA51_FOUND AND NOT LUA52_FOUND) set(LUABIND_LUA_VERSION "" CACHE STRING "51 or 52; empty to use 51 if 52 cannot be found and 52 otherwise.") if(LUABIND_LUA_VERSION) find_package("Lua${LUABIND_LUA_VERSION}" REQUIRED) else() find_package(Lua52) if(NOT LUA52_FOUND) find_package(Lua51) if(NOT LUA51_FOUND) message(FATAL_ERROR "Neither Lua 5.1 nor 5.2 could be found.") endif() endif() endif() set(LUA_INCLUDE_DIRS "${LUA_INCLUDE_DIR}") endif() if(NOT MSVC) check_cxx_compiler_flag(-std=c++11 LUABIND_HAS_CXX11) if (LUABIND_HAS_CXX11) set (LUABIND_CXX11_COMPILER_FLAGS "-std=c++11") else() message("Compiler does not support -std=c++11 flag, C++11 disabled.") endif() elseif(MSVC_VERSION GREATER 1699) # 1700 = VS 11 (2012) set (LUABIND_HAS_CXX11 ON) else() set (LUABIND_HAS_CXX11 OFF) message("MSVC < 11 (2012) detected, C++11 disabled.") endif() if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) # We are the top-level project option(LUABIND_INSTALL "Install the LuaBind library and headers" ON) option(LUABIND_APPEND_VERSION_SUFFIX "Append a version suffix to the library name (like luabind09)?" ON) option(LUABIND_NO_ERROR_CHECKING "Build so that all the Lua code is expected only to make legal calls?" OFF) option(LUABIND_NO_EXCEPTIONS "Disable all usage of try, catch, and throw?" OFF) option(LUABIND_CPLUSPLUS_LUA "Was Lua built as C++?" OFF) option(LUABIND_DYNAMIC_LINK "Build luabind as a shared library?" OFF) option(LUABIND_NOT_THREADSAFE "Permit the use of static variables, thus making Luabind usable only from one of your system threads." OFF) option(LUABIND_ENABLE_WARNINGS "Enable extra warnings during the build of the library and tests" ON) if (LUABIND_HAS_CXX11) option(LUABIND_USE_CXX11 "Build Luabind using C++11 features?" ON) else() set(LUABIND_USE_CXX11 OFF) endif() if(Boost_VERSION LESS 104700) set(LUABIND_USE_NOEXCEPT_DEF OFF) # 1900 = VS 14 (2015) if (LUABIND_CXX11_DEFAULT AND NOT MSVC OR MSVC_VERSION GREATER 1899) set(LUABIND_USE_NOEXCEPT_DEF ON) endif() option(LUABIND_USE_NOEXCEPT "If your compiler is C++11 compliant, but you're using old Boost, you need to set this." ${LUABIND_USE_NOEXCEPT_DEF}) unset(LUABIND_USE_NOEXCEPT_DEF) endif() if(LUABIND_USE_CXX11 AND NOT LUABIND_HAS_CXX11) # The compiler supports no C++11 set(LUABIND_USE_CXX11 OFF CACHE BOOL "Build Luabind using C++11 features?" FORCE) endif() if(LUABIND_USE_CXX11) option(LUABIND_NO_SCOPED_ENUM "Indicates that your compiler and standard library lacks scoped enums and std::underlying_type" OFF) set(LUABIND_NO_STD_SHARED_PTR OFF) else() # No CXX11, can't have scoped enum # TODO is this right? #set(LUABIND_NO_SCOPED_ENUM ON CACHE INTERNAL "" FORCE) option(LUABIND_NO_STD_SHARED_PTR "Indicates that your standard library lacks C++11 shared_ptr in std namespace" ON) endif() endif() if(LUABIND_NO_STD_SHARED_PTR) add_definitions(-DLUABIND_NO_STD_SHARED_PTR) endif() if(LUABIND_USE_CXX11) add_definitions(-DLUABIND_USE_CXX11) endif() # Configure the build info header file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/luabind") configure_file(build_information.hpp.cmake_in "${CMAKE_CURRENT_BINARY_DIR}/luabind/build_information.hpp") # Set up the build set(BUILD_SHARED_LIBS ${LUABIND_DYNAMIC_LINK}) if(LUABIND_USE_CXX11 AND LUABIND_CXX11_COMPILER_FLAGS) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${LUABIND_CXX11_COMPILER_FLAGS}") elseif(NOT LUABIND_USE_CXX11 AND NOT MSVC) check_cxx_compiler_flag(-std=c++98 LUABIND_HAS_CXX98FLAG) if (LUABIND_HAS_CXX98FLAG) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++98") endif() endif() # Test and enable warning flags if desired, as well as other compiler flag macro(_luabind_add_flag _flag _var) check_cxx_compiler_flag(${_flag} ${_var}) if(${_var}) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${_flag}") endif() endmacro() if(MSVC) # multi-process compile _luabind_add_flag(/MP SUPPORTS_MP_FLAG) if(LUABIND_ENABLE_WARNINGS) # Warning level 4 _luabind_add_flag(/W4 SUPPORTS_W4_FLAG) # Disable incorrect warning C4709 # ("comma operator within array index expression") _luabind_add_flag(/wd4709 SUPPORTS_WD4709_FLAG) IF (MSVC_VERSION GREATER 1899) # 1900 = MSVC 14 (2015) # Disable overly pendantic warning C4459 "declaration of 'var' hides # global declaration" which is issued a lot for 'result' which is # globally declared for policies. See also # https://connect.microsoft.com/VisualStudio/feedback/details/1355600/. _luabind_add_flag(/wd4459 SUPPORTS_WD4459_FLAG) # Disable warning C4913 "user defined binary operator ',' exists but # no overload could convert all operands, default built-in binary # operator ',' used" which is triggered even when no comma is # involved at all, refering to the 'T const& x, # operator_void_return' overload in luabind::detail. _luabind_add_flag(/wd4913 SUPPORTS_WD4913_FLAG) endif() endif() else() set(possible_flags) if(BUILD_SHARED_LIBS) list(APPEND possible_flags fvisibility=hidden) endif() if(LUABIND_ENABLE_WARNINGS) list(APPEND possible_flags Wall Wextra Wno-deprecated-declarations # auto_ptr is OK for now Wno-unused-macros Wlogical-op Wmissing-declarations Wsign-conversion pedantic Wcast-align Wcast-qual Wctor-dtor-privacy Winit-self Wdisabled-optimizations Wformat=2 Wmissing-include-dirs Wold-style-cast Woverloaded-virtual Wredundant-decls Wshadow Wsign-promo Wstrict-null-sentinel Wstrict-overflow=5) if(LUABIND_USE_CXX11) list(APPEND possible_flags Wnoexcept) endif() if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") list(APPEND possible_flags Weverything Wno-unused-local-typedef Wno-shadow Wno-undef Wno-global-constructors Wno-weak-vtables Wno-padded Wno-exit-time-destructors Wno-missing-noreturn) if(LUABIND_USE_CXX11) list(APPEND possible_flags Wno-zero-as-nullpointer Wno-c++98-compat Wno-c++98-compat-pedantic) else() list(APPEND possible_flags Wno-c++11-long-long) endif() elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND NOT LUABIND_USE_CXX11) list(APPEND possible_flags Wno-long-long) endif() endif() if(possible_flags) foreach(_flag ${possible_flags}) string(REGEX REPLACE [-+=] _ sanitized_flag ${_flag}) _luabind_add_flag(-${_flag} SUPPORTS_${sanitized_flag}_FLAG) endforeach() endif() endif() include_directories(BEFORE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_BINARY_DIR}") include_directories(AFTER SYSTEM ${Boost_INCLUDE_DIRS} ${LUA_INCLUDE_DIRS}) add_subdirectory(src) # Set up testing and documentation, only if we are the top-level project. if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) include(CTest) if(BUILD_TESTING) add_subdirectory(test) endif() add_subdirectory(doc) endif() if(LUABIND_INSTALL) if(WIN32 AND NOT CYGWIN) set(INSTALL_CMAKE_DIR CMake) set(INSTALL_CMAKE_DIR_LUA CMake) else() set(INSTALL_CMAKE_DIR lib/CMake/Luabind) set(INSTALL_CMAKE_DIR_LUA lib/CMake/Lua52) endif() install(FILES "cmake/Modules/FindLuabind.cmake" DESTINATION ${INSTALL_CMAKE_DIR}) install(FILES "cmake/Modules/FindLua52.cmake" DESTINATION ${INSTALL_CMAKE_DIR_LUA}) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/luabind/build_information.hpp" DESTINATION include/luabind) endif() luabind-1.1.1/INSTALL.txt000066400000000000000000000040061366245310300150020ustar00rootroot00000000000000Note: The information in this file is outdated. Use CMake instead. luabind installation ==================== The build system used by luabind is Boost Build V2, which can be found at: http://www.boost.org/doc/tools/build/index.html The installation instructions are available at: http://www.boost.org/doc/tools/build/doc/html/bbv2/installation.html If you are using Debian or Ubuntu, you can simply install the "boost-build" package: $ sudo apt-get install boost-build Other distributions may have similar packages. On Windows, you can download pre-built "bjam" binaries, and follow the installation instructions on the page linked above. Windows ------- The environment variable "BOOST_ROOT" must be set to the directory where Boost was extracted. "LUA_PATH" must be set to a directory where Lua binaries and headers reside. The recommended way to get the Lua libraries is to download the "DLL and Includes" package from: http://luabinaries.luaforge.net/download.html With these environment variables properly set: $ set BOOST_ROOT=... $ set LUA_PATH=... $ bjam stage Will build the default library variants and place them in a directory called "stage". This can be controlled with the "--stagedir" option: $ bjam --stagedir=libs stage Would place the libraries in a "libs" directory. Note that there is nothing magic going on here. If you don't want to build the libraries this way, or run the tests, there is nothing stopping you from using whatever build system you want. For example, simply dropping the source files in a Visual Studio project should just work. The only requirement is that "LUABIND_DYNAMIC_LINK" must be defined when building and linking to a shared library. \*nix ----- $ bjam install Will build and install the default library variants, and install them together with the header files to the default prefix, which is "/usr/local". The install prefix can be controlled with the "--prefix" option. For example: $ bjam --prefix=/usr install Will install to "/usr/lib" and "/usr/include". luabind-1.1.1/LICENSE.txt000066400000000000000000000022671366245310300147650ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // Copyright (c) 2012, 2013 Christian Neumüller [bugfixes, small additions] // 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. luabind-1.1.1/README.md000066400000000000000000000164641366245310300144250ustar00rootroot00000000000000Luabind ======= [![Travis CI build status](https://travis-ci.com/Oberon00/luabind.svg?branch=master)](https://travis-ci.com/github/Oberon00/luabind) Luabind is a library that helps you create bindings between C++ and Lua. It has the ability to expose functions and classes, written in C++, to Lua. It will also supply the functionality to define classes in lua and let them derive from other lua classes or C++ classes. Lua classes can override virtual functions from their C++ baseclasses. It is written towards Lua 5.x, and does not work with Lua 4. It is implemented utilizing template meta programming. That means that you don't need an extra preprocess pass to compile your project (it is done by the compiler). 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][1]. > Copyright Daniel Wallin, Arvid Norberg 2003. > Extracted from [1]: http://www.opensource.org/licenses/mit-license.php This fork --------- I forked the project since it seems abandoned (latest commit from January 2012 on the 0.9 branch) and I ran into certain bugs which needed fixing (see commits). This should actually have been forked from [rpavlik/luabind][rpavlik]: I cherry-picked most commits from there. Additionally, many commits from [fhoefler/luaponte][fhoefling] are incorporated (as the are in rpavlik's fork). Thus, feel free to do the same with my fork. [rpavlik]: http://github.com/rpavlik/luabind/ [fhoefling]: http://github.com/fhoefling/luaponte In the following two sections, the improvements over the latest official luabind release (0.9) are described. ### Fixed bugs ### * Destroyed objects now have their metatable unset. Previously, one could easily cause segmentation faults and other undefined behavior by accessing destroyed objects from luabinds `__finalize` or Lua 5.2's `__gc`. Now you can simply check with `getmetatable(obj)`, and if you forget, you get an ordinary, well defined Lua error instead. Commit [a83aa][c-destroy]. * The Lua part of a `wrap_base` derived class randomly got lost after a few garbage collection cycles due to errors in the implementation of the internal `weak_ref` class. Credits for the fix go to Max McGuire who [posted][mmg-fix] a fix on luabind-user in 2010. Commit [a3a400][c-weakref]. * The error message displayed when a function could not be called from Lua with the provided arguments sometimes only contained the function signatures but not the actual error message. mrwonko's commit [9d15e0][c-errmsg] (and previous). * Luabind did not work over shared library (DLL) boundaries on some platforms. fhoefling's commit [a83af3][c-dll] and my minor improvement [a8349d][c-dll2]. * Calling `call_function` with a return type but not using it resulted in a call to `std::terminate` if the called function produced an error and a C++11 compliant compiler is used. Commit [81bdcb][c-noexpect]. * Luabind failed to recognize Lua numbers correctly on MSVC x64. Commit [c9582c][c-longlong]. * Luabind failed to compile on g++ with Boost 1.49 (`BOOST_PP_ITERATION_FLAGS` problem). The first one I know to have fixed this is [fhoefling][c-fh-gcc-ftbfs]. Commit [1aa80b][c-gcc-ftbsfs]. * Luabind failed to compile on Clang. Commit [4555b2][c-clang-ftbfs]. [c-destroy]: http://github.com/Oberon00/luabind/commit/a83aae710ccb5d4fad2d625e3c87008d450949cb [mmg-fix]: http://lua.2524044.n2.nabble.com/weak-ref-issue-patch-td7581558.html [c-weakref]: http://github.com/Oberon00/luabind/commit/a3a400e5fc5f31b5733ad0e595e7f5b474883174 [c-fh-gcc-ftbfs]: http://github.com/fhoefling/luaponte/commit/085f2e06204d6b2710db127806cfa855fca17d79 [c-gcc-ftbsfs]: http://github.com/Oberon00/luabind/commit/1aa80be0bb944e960919542b16c6a3a117a4cdb8 [c-errmsg]: http://github.com/Oberon00/luabind/commit/9d15e0288261ef83b227a3151d8f2ac238ef3759 [c-dll]: http://github.com/Oberon00/luabind/commit/a83af3c69a3cd6da5ba21ea5062205fa664e59d2 [c-dll2]: http://github.com/Oberon00/luabind/commit/a8349dfd94bcc456af5dc4b1bf4f175875d8ae54 [c-longlong]: http://github.com/Oberon00/luabind/commit/c9582cea44fd67301ee5940cf08ccf5ae8c90094 [c-noexpect]: http://github.com/Oberon00/luabind/commit/81bdcb72aa6ef7b321e59416b77be65c3944d6a9 [c-clang-ftbfs]: http://github.com/Oberon00/luabind/commit/4555b20f0553f073d9d9085a43174aea5f7abaa6 ### Added features ### * CMake replaces the broken Jamfile as build system (including installation and test support). A [`FindLuabind.cmake`][findluabind] file is also provided, as well as [`FindLua52.cmake`][findlua52]. * A bit of C++11 support: + `std::shared_ptr` is supported as smart pointer through [`luabind/std_shared_ptr_converter.hpp`][stdptr]. Commit [118f80][c-11-ptr]. + Scoped enums can be used with `enum_`. + Basic rvalue reference support. fhoefling's commit [a83af3][c-11-rval]. + Support for `long long`. Commit [c9582c][c-longlong] (also for pre-C++11 compilers supporting it). * A new (C++) function `set_package_preload` can be used to register a (loader) function to be called only if it is `require`d from Lua. rpavlik's commit [3502e9][c-preload]. * Modules can now register everything to arbitrary tables (`luabind::object`s). fhoefling's commit [dd4a16][c-table]. This plays together very nicely with `set_package_preload`. * The modulo operator `%` can now be exported to Lua. rpavlik's commit [855b4a][c-modulo] and the following. * `class_info` can now handle actual classes as arguments. Previously it could handle only *objects* of luabind classes. rpavlik's commit [c2ee1f][c-classinfo]. [findluabind]: cmake/Modules/FindLuabind.cmake [findlua52]: cmake/Modules/FindLua52.cmake [stdptr]: luabind/std_shared_ptr_converter.hpp [c-11-ptr]: http://github.com/Oberon00/luabind/commit/118f808b068e93e78fc717749f757a2358b9a4af [c-11-rval]: http://github.com/Oberon00/luabind/commit/a83af3c69a3cd6da5ba21ea5062205fa664e59d2 [c-classinfo]: http://github.com/Oberon00/luabind/commit/c2ee1f82598eb3ded6922e05decdcc7bb69a8d2a [c-preload]: http://github.com/Oberon00/luabind/commit/3502e9c7234daf1b12f6dc7f545d361d5cee105d [c-table]: http://github.com/Oberon00/luabind/commit/dd4a1695dcbabbe1541f229ff245178b0621cf0d [c-modulo]: http://github.com/Oberon00/luabind/commit/855b4afba0204d0ae6e8fbd251dfc71f4d84353e Additionally, the removal of many lines of death code, also unused (parts of) member variables and other minor improvements make luabind generally (a little bit) faster and less memory hungry. Many compiler warnings have also been fixed. The remaining (irrelevant) ones are silenced, so the build should be completely warning- (and of course error-)free on Clang, g++ and MSVC. This fork is fully source (API) compatible to the original luabind library, but not binary compatible. ### A word on the branch names ### First I worked against the 0.9 branch but then decided to rename it to master, since it actually has become the master branch of development in this fork. The original master branch is now named old-master. luabind-1.1.1/build_information.hpp.cmake_in000066400000000000000000000037601366245310300211230ustar00rootroot00000000000000/** @file @brief Generated header containing build options that change the library contents. @date 2013 @author Ryan Pavlik and http://academic.cleardefinition.com/ Iowa State University Virtual Reality Applications Center Human-Computer Interaction Graduate Program */ // Copyright Iowa State University 2013. // 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. #ifndef INCLUDED_BuildInformation_hpp_GUID_90CCCE9E_4374_4090_36BA_3AA2C22271F7 #define INCLUDED_BuildInformation_hpp_GUID_90CCCE9E_4374_4090_36BA_3AA2C22271F7 #cmakedefine LUABIND_NO_ERROR_CHECKING 1 #cmakedefine LUABIND_NO_EXCEPTIONS 1 #cmakedefine LUABIND_CPLUSPLUS_LUA 1 #cmakedefine LUABIND_USE_NOEXCEPT 1 #cmakedefine LUABIND_NOT_THREADSAFE 1 #cmakedefine LUABIND_DYNAMIC_LINK 1 /// TODO does this actually change the ABI? #cmakedefine LUABIND_NO_SCOPED_ENUM 1 #endif // INCLUDED_BuildInformation_hpp_GUID_90CCCE9E_4374_4090_36BA_3AA2C22271F7 luabind-1.1.1/cmake/000077500000000000000000000000001366245310300142135ustar00rootroot00000000000000luabind-1.1.1/cmake/Modules/000077500000000000000000000000001366245310300156235ustar00rootroot00000000000000luabind-1.1.1/cmake/Modules/FindLua52.cmake000066400000000000000000000105261366245310300203220ustar00rootroot00000000000000# Locate Lua library # This module defines # LUA52_FOUND, if false, do not try to link to Lua # LUA_LIBRARIES # LUA_INCLUDE_DIR, where to find lua.h # LUA_VERSION_STRING, the version of Lua found (since CMake 2.8.8) # # Note that the expected include convention is # #include "lua.h" # and not # #include # This is because, the lua location is not standardized and may exist # in locations other than lua/ #============================================================================= # CMake - Cross Platform Makefile Generator # Copyright 2007-2009 Kitware, Inc. # # Adjusted for Lua 5.2 (from 5.1) by Christian Neumüller # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the names of Kitware, Inc., the Insight Software Consortium, # nor the names of their contributors may be used to endorse or promote # products derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #============================================================================= FIND_PATH(LUA_INCLUDE_DIR lua.h HINTS $ENV{LUA_DIR} PATH_SUFFIXES include/lua52 include/lua5.2 include/lua include PATHS ~/Library/Frameworks /Library/Frameworks /sw # Fink /opt/local # DarwinPorts /opt/csw # Blastwave /opt ) FIND_LIBRARY(_LUA_LIBRARY_RELEASE NAMES lua52 lua5.2 lua-5.2 lua HINTS $ENV{LUA_DIR} PATH_SUFFIXES lib64 lib PATHS ~/Library/Frameworks /Library/Frameworks /sw /opt/local /opt/csw /opt ) FIND_LIBRARY(_LUA_LIBRARY_DEBUG NAMES lua52-d lua5.2-d lua-5.2-d lua-d HINTS $ENV{LUA_DIR} PATH_SUFFIXES lib64 lib PATHS ~/Library/Frameworks /Library/Frameworks /sw /opt/local /opt/csw /opt ) IF(_LUA_LIBRARY_RELEASE OR _LUA_LIBRARY_DEBUG) IF(_LUA_LIBRARY_RELEASE AND _LUA_LIBRARY_DEBUG) SET(_LUA_LIBRARY optimized ${_LUA_LIBRARY_RELEASE} debug ${_LUA_LIBRARY_DEBUG}) ELSEIF(_LUA_LIBRARY_RELEASE) SET(_LUA_LIBRARY ${_LUA_LIBRARY_RELEASE}) ELSE() SET(_LUA_LIBRARY ${_LUA_LIBRARY_DEBUG}) ENDIF() IF(UNIX AND NOT APPLE) FIND_LIBRARY(_LUA_MATH_LIBRARY m) mark_as_advanced(_LUA_MATH_LIBRARY) ENDIF(UNIX AND NOT APPLE) # For Windows and Mac, don't need to explicitly include the math library ENDIF() IF(_LUA_LIBRARY) SET(LUA_LIBRARIES "${_LUA_LIBRARY}" "${_LUA_MATH_LIBRARY}" CACHE STRING "Lua 5.2 Libraries") ENDIF(_LUA_LIBRARY) IF(LUA_INCLUDE_DIR AND EXISTS "${LUA_INCLUDE_DIR}/lua.h") FILE(STRINGS "${LUA_INCLUDE_DIR}/lua.h" lua_version_str REGEX "^#define[ \t]+LUA_RELEASE[ \t]+\"Lua .+\"") STRING(REGEX REPLACE "^#define[ \t]+LUA_RELEASE[ \t]+\"Lua ([^\"]+)\".*" "\\1" LUA_VERSION_STRING "${lua_version_str}") UNSET(lua_version_str) ENDIF() INCLUDE(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake) # handle the QUIETLY and REQUIRED arguments and set LUA_FOUND to TRUE if # all listed variables are TRUE FIND_PACKAGE_HANDLE_STANDARD_ARGS(Lua52 REQUIRED_VARS LUA_INCLUDE_DIR LUA_LIBRARIES VERSION_VAR LUA_VERSION_STRING) MARK_AS_ADVANCED(LUA_INCLUDE_DIR LUA_LIBRARIES LUA_LIBRARY LUA_MATH_LIBRARY _LUA_LIBRARY_RELEASE _LUA_LIBRARY_DEBUG) luabind-1.1.1/cmake/Modules/FindLuabind.cmake000066400000000000000000000024631366245310300210110ustar00rootroot00000000000000# Locate Luabind library FIND_PATH(LUABIND_INCLUDE_DIRS luabind/luabind.hpp HINTS $ENV{LUABIND_DIR} PATH_SUFFIXES include/luabind09 include/luabind include ) FIND_LIBRARY(_LUABIND_LIBRARY_RELEASE NAMES luabind09 luabind-0.9 luabind HINTS $ENV{LUABIND_DIR} PATH_SUFFIXES lib64 lib ) FIND_LIBRARY(_LUABIND_LIBRARY_DEBUG NAMES luabind09-d luabind-0.9-d luabind-d HINTS $ENV{LUABIND_DIR} PATH_SUFFIXES lib64 lib ) IF(_LUABIND_LIBRARY_RELEASE OR _LUABIND_LIBRARY_DEBUG) IF(_LUABIND_LIBRARY_RELEASE AND _LUABIND_LIBRARY_DEBUG) SET(_LUABIND_LIBRARY optimized ${_LUABIND_LIBRARY_RELEASE} debug ${_LUABIND_LIBRARY_DEBUG}) ELSEIF(_LUABIND_LIBRARY_RELEASE) SET(_LUABIND_LIBRARY ${_LUABIND_LIBRARY_RELEASE}) ELSE() SET(_LUABIND_LIBRARY ${_LUABIND_LIBRARY_DEBUG}) ENDIF() ENDIF() IF(_LUABIND_LIBRARY) SET(LUABIND_LIBRARIES "${_LUABIND_LIBRARY}" CACHE STRING "Luabind Libraries") ENDIF(_LUABIND_LIBRARY) INCLUDE(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake) # handle the QUIETLY and REQUIRED arguments and set LUABIND_FOUND to TRUE if # all listed variables are TRUE FIND_PACKAGE_HANDLE_STANDARD_ARGS(Luabind REQUIRED_VARS LUABIND_INCLUDE_DIRS LUABIND_LIBRARIES) MARK_AS_ADVANCED(LUABIND_INCLUDE_DIRS LUABIND_LIBRARIES) luabind-1.1.1/doc/000077500000000000000000000000001366245310300137005ustar00rootroot00000000000000luabind-1.1.1/doc/CMakeLists.txt000066400000000000000000000041471366245310300164460ustar00rootroot00000000000000# Embedded build for LuaBind # 2009-2011 Ryan Pavlik # http://academic.cleardefinition.com/ # Iowa State University HCI Graduate Program/VRAC set(SOURCES conf.py acknowledgments.rst basic-usage.rst build-options.rst building.rst classes.rst errors.rst exceptions.rst faq.rst functions.rst impl-notes.rst index.rst intro.rst issues.rst lua-classes.rst object.rst policies.rst scopes.rst split-registration.rst userdefined-converters.rst policies/adopt.rst policies/copy.rst policies/dependency.rst policies/discard_result.rst policies/out_value.rst policies/pure_out_value.rst policies/raw.rst policies/return_reference_to.rst policies/return_stl_iterator.rst policies/yield.rst) if (WIN32) list (APPEND SOURCES make.bat) set(SPHINX_CMD "${CMAKE_CURRENT_BINARY_DIR}/make.bat" html) else() list (APPEND SOURCES Makefile) set(SPHINX_CMD make html) endif() set(SOURCES_COPIED) foreach(SOURCE ${SOURCES}) set(CURRENT_SOURCE_O "${CMAKE_CURRENT_BINARY_DIR}/${SOURCE}") add_custom_command(OUTPUT ${CURRENT_SOURCE_O} COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/${SOURCE}" ${CURRENT_SOURCE_O} DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${SOURCE}" COMMENT "Copying ${SOURCE}") list(APPEND SOURCES_COPIED ${CURRENT_SOURCE_O}) endforeach() include(GetGitRevisionDescription.cmake) git_describe(GIT_DESCRIPTION) if(GIT_DESCRIPTION) string(REGEX REPLACE "^v" "" DOCS_VERSION "${GIT_DESCRIPTION}") else() set(DOCS_VERSION "${CPACK_PACKAGE_VERSION}") endif() configure_file(git_version.in "${CMAKE_CURRENT_BINARY_DIR}/git_version") list(APPEND SOURCES "${CMAKE_CURRENT_BINARY_DIR}/git_version.py") add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_build/" COMMAND ${SPHINX_CMD} WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" DEPENDS ${SOURCES_COPIED} VERBATIM COMMENT "Generating HTML documentation with sphinx makefile/script.") add_custom_target(doc DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/_build/") luabind-1.1.1/doc/GetGitRevisionDescription.cmake000066400000000000000000000077301366245310300220170ustar00rootroot00000000000000# - Returns a version string from Git # # These functions force a re-configure on each git commit so that you can # trust the values of the variables in your build system. # # get_git_head_revision( [ ...]) # # Returns the refspec and sha hash of the current head revision # # git_describe( [ ...]) # # Returns the results of git describe on the source tree, and adjusting # the output so that it tests false if an error occurs. # # git_get_exact_tag( [ ...]) # # Returns the results of git describe --exact-match on the source tree, # and adjusting the output so that it tests false if there was no exact # matching tag. # # Requires CMake 2.6 or newer (uses the 'function' command) # # Original Author: # 2009-2010 Ryan Pavlik # http://academic.cleardefinition.com # Iowa State University HCI Graduate Program/VRAC # # Copyright Iowa State University 2009-2010. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) if(__get_git_revision_description) return() endif() set(__get_git_revision_description YES) # We must run the following at "include" time, not at function call time, # to find the path to this module rather than the path to a calling list file get_filename_component(_gitdescmoddir ${CMAKE_CURRENT_LIST_FILE} PATH) function(get_git_head_revision _refspecvar _hashvar) set(GIT_PARENT_DIR "${CMAKE_SOURCE_DIR}") set(GIT_DIR "${GIT_PARENT_DIR}/.git") while(NOT EXISTS "${GIT_DIR}") # .git dir not found, search parent directories set(GIT_PREVIOUS_PARENT "${GIT_PARENT_DIR}") get_filename_component(GIT_PARENT_DIR ${GIT_PARENT_DIR} PATH) if(GIT_PARENT_DIR STREQUAL GIT_PREVIOUS_PARENT) # We have reached the root directory, we are not in git set(${_refspecvar} "GITDIR-NOTFOUND" PARENT_SCOPE) set(${_hashvar} "GITDIR-NOTFOUND" PARENT_SCOPE) return() endif() set(GIT_DIR "${GIT_PARENT_DIR}/.git") endwhile() set(GIT_DATA "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/git-data") if(NOT EXISTS "${GIT_DATA}") file(MAKE_DIRECTORY "${GIT_DATA}") endif() if(NOT EXISTS "${GIT_DIR}/HEAD") return() endif() set(HEAD_FILE "${GIT_DATA}/HEAD") configure_file("${GIT_DIR}/HEAD" "${HEAD_FILE}" COPYONLY) configure_file("${_gitdescmoddir}/GetGitRevisionDescription.cmake.in" "${GIT_DATA}/grabRef.cmake" @ONLY) include("${GIT_DATA}/grabRef.cmake") set(${_refspecvar} "${HEAD_REF}" PARENT_SCOPE) set(${_hashvar} "${HEAD_HASH}" PARENT_SCOPE) endfunction() function(git_describe _var) if(NOT GIT_FOUND) find_package(Git QUIET) endif() get_git_head_revision(refspec hash) if(NOT GIT_FOUND) set(${_var} "GIT-NOTFOUND" PARENT_SCOPE) return() endif() if(NOT hash) set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE) return() endif() # TODO sanitize #if((${ARGN}" MATCHES "&&") OR # (ARGN MATCHES "||") OR # (ARGN MATCHES "\\;")) # message("Please report the following error to the project!") # message(FATAL_ERROR "Looks like someone's doing something nefarious with git_describe! Passed arguments ${ARGN}") #endif() #message(STATUS "Arguments to execute_process: ${ARGN}") execute_process(COMMAND "${GIT_EXECUTABLE}" describe ${hash} ${ARGN} WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" RESULT_VARIABLE res OUTPUT_VARIABLE out ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) if(NOT res EQUAL 0) set(out "${out}-${res}-NOTFOUND") endif() set(${_var} "${out}" PARENT_SCOPE) endfunction() function(git_get_exact_tag _var) git_describe(out --exact-match ${ARGN}) set(${_var} "${out}" PARENT_SCOPE) endfunction() luabind-1.1.1/doc/GetGitRevisionDescription.cmake.in000066400000000000000000000023361366245310300224210ustar00rootroot00000000000000# # Internal file for GetGitRevisionDescription.cmake # # Requires CMake 2.6 or newer (uses the 'function' command) # # Original Author: # 2009-2010 Ryan Pavlik # http://academic.cleardefinition.com # Iowa State University HCI Graduate Program/VRAC # # Copyright Iowa State University 2009-2010. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) set(HEAD_HASH) file(READ "@HEAD_FILE@" HEAD_CONTENTS LIMIT 1024) string(STRIP "${HEAD_CONTENTS}" HEAD_CONTENTS) if(HEAD_CONTENTS MATCHES "ref") # named branch string(REPLACE "ref: " "" HEAD_REF "${HEAD_CONTENTS}") if(EXISTS "@GIT_DIR@/${HEAD_REF}") configure_file("@GIT_DIR@/${HEAD_REF}" "@GIT_DATA@/head-ref" COPYONLY) elseif(EXISTS "@GIT_DIR@/logs/${HEAD_REF}") configure_file("@GIT_DIR@/logs/${HEAD_REF}" "@GIT_DATA@/head-ref" COPYONLY) set(HEAD_HASH "${HEAD_REF}") endif() else() # detached HEAD configure_file("@GIT_DIR@/HEAD" "@GIT_DATA@/head-ref" COPYONLY) endif() if(NOT HEAD_HASH) file(READ "@GIT_DATA@/head-ref" HEAD_HASH LIMIT 1024) string(STRIP "${HEAD_HASH}" HEAD_HASH) endif() luabind-1.1.1/doc/Makefile000066400000000000000000000151561366245310300153500ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Luabind.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Luabind.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Luabind" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Luabind" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." luabind-1.1.1/doc/acknowledgments.rst000066400000000000000000000014111366245310300176140ustar00rootroot00000000000000Acknowledgments =============== Written by Daniel Wallin and Arvid Norberg. © Copyright 2003. All rights reserved. Evan Wies has contributed with thorough testing, countless bug reports and feature ideas. Many features and fixes of this fork come from `Ryan Pavlik's (rpavlik) fork`__ and from `Peter Colberg (fhoefling's fork)`__. .. __: https://github.com/rpavlik/luabind/ .. __: https://github.com/fhoefling/luaponte/ Christian Neumüller (Oberon00) is the maintainer of `this fork`_. .. _this fork: http://github.com/Oberon00/luabind/ A rather complete list of contributors can be found at http://github.com/Oberon00/luabind/contributors. This library was highly inspired by Dave Abrahams' Boost.Python_ library. .. _Boost.Python: http://www.boost.org/libs/pythonluabind-1.1.1/doc/basic-usage.rst000066400000000000000000000033721366245310300166220ustar00rootroot00000000000000Basic usage =========== To use luabind, you must include ``lua.h`` and luabind's main header file:: extern "C" { #include "lua.h" } #include This includes support for both registering classes and functions. If you just want to have support for functions or classes you can include ``luabind/function.hpp`` and ``luabind/class.hpp`` separately:: #include #include The first thing you need to do is to call ``luabind::open(lua_State*)`` which will register the functions to create classes from Lua, and initialize some state-global structures used by luabind. If you don't call this function you will hit asserts later in the library. There is no corresponding close function because once a class has been registered in Lua, there really isn't any good way to remove it. Partly because any remaining instances of that class relies on the class being there. Everything will be cleaned up when the state is closed 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 ````. If you for some reason need to include another Lua header, you can modify this file. Hello world ----------- :: #include #include 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; } .. code-block:: lua Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio > loadlib('hello_world.dll', 'init')() > greet() Hello world! > luabind-1.1.1/doc/build-options.rst000066400000000000000000000132421366245310300172240ustar00rootroot00000000000000.. _part-build-options: Build options ============= There are a number of configuration options (preprocessor ``#define``\ s available when building luabind. It is very important that your project has the exact same configuration options as the ones given when the library was build! The exceptions are the ``LUABIND_MAX_ARITY`` and ``LUABIND_MAX_BASES`` which are template-based options and only matters when you use the library (which means they can differ from the settings of the library). To achieve this you should use the CMake equivalent of these options. Then, when building with CMake the ``build_information.hpp`` header is created and automatically included by ``config.hpp``, thus keeping the options in sync automatically. ``LUABIND_MAX_ARITY`` Controls the maximum arity of functions that are registered with luabind. You can't register functions that takes more parameters than the number this macro is set to. It defaults to 5, so, if your functions have greater arity you have to redefine it. A high limit will increase compilation time. ``LUABIND_MAX_BASES`` Controls the maximum number of classes one class can derive from in luabind (the number of classes specified within ``bases<>``). ``LUABIND_MAX_BASES`` defaults to 4. A high limit will increase compilation time. ``LUABIND_NO_ERROR_CHECKING`` If this macro is defined, all the Lua code is expected only to make legal calls. If illegal function calls are made (e.g. giving parameters that doesn't match the function signature) they will not be detected by luabind and the application will probably crash. Error checking could be disabled when shipping a release build (given that no end-user has access to write custom Lua code). Note that function parameter matching will be done if a function is overloaded, since otherwise it's impossible to know which one was called. Functions will still be able to throw exceptions when error checking is disabled. If a function throws an exception it will be caught by luabind and propagated with ``lua_error()``. ``LUABIND_NO_EXCEPTIONS`` This define will disable all usage of try, catch and throw in luabind. This will in many cases disable run-time errors, when performing invalid casts or calling Lua functions that fails or returns values that cannot be converted by the given policy. luabind requires that no function called directly or indirectly by luabind throws an exception (throwing exceptions through Lua has undefined behavior). Where exceptions are the only way to get an error report from luabind, they will be replaced with calls to the callback functions set with ``set_error_callback()`` and ``set_cast_failed_callback()``. ``LUA_API`` If you want to link dynamically against Lua, you can set this define to the import-keyword on your compiler and platform. On Windows in Visual Studio this should be ``__declspec(dllimport)`` if you want to link against Lua as a dll. ``LUABIND_DYNAMIC_LINK`` Must be defined if you intend to link against the luabind shared library (.so or DLL) / build it as such. Note that in future versions of luabind, this option may be dependent on ``BUILD_SHARED_LIBS`` in CMake, so you should always set both CMake options to the same value. If enabling this, you should link Lua dynamically to both Luabind and your application. If you encounter double-free errors or other memory corruption, this might be the problem. ``LUABIND_CPLUSPLUS_LUA`` Without this, all included Lua headers will be wrapped in ``extern "C"``. Define this if you compiled Lua as C++. ``NDEBUG`` This define will disable all asserts and should be defined in a release build. ``LUABIND_USE_NOEXCEPT`` If you use Boost <= 1.46 but your compiler is C++11 compliant and marks destructors as noexcept by default, you need to define LUABIND_USE_NOEXCEPT. Failing to do so will cause std::terminate() being called if a destructor throws (e.g. the destructor of the proxy returned by ``call_function`` or ``object::operator()``). CMake options ~~~~~~~~~~~~~ The following options can be given to CMake when building luabind. You can either specify them directly on the commandline using ``-Doption=value`` or let CMake ask you for each of them by invoking it with the ``-i`` flag. On Windows, you will usually prefer ``cmake-gui``. All options are booleans, unless specified otherwise. ``LUABIND_ENABLE_WARNINGS`` Enable compiler warnings during the build of luabind and the tests. ``LUABIND_USE_CXX11`` This controls whether the ``-std=c++11`` flag is passed to compilers that support it. And whether support for C++11 scoped enums can be enabled. ``BUILD_TESTING`` Whether to generate build files for the unit tests (they must be run manually in any case). ``LUABIND_BUILD_HEADER_TESTS`` Enable this for (many) additional compilation tests: Each of Luabind’s public headers will be included in a generated .cpp file which otherwise only contains an empty main function, meaning that one dummy binary per header file is generated. This can only be enabled if ``BUILD_TESTING`` is enabled. ``LUABIND_APPEND_VERSION_SUFFIX`` With this option set (the default), built binaries and object archives will be named e.g. ``luabind09.dll`` instead of just ``luabind.dll``. ``LUABIND_LUA_VERSION`` A string variable with defaults to ``""`` (the empty string). It can be set to ``"51"`` or ``"52"`` to use the respective Lua versions. If left empty, Lua52 will be tried first before falling back to Lua51. ``CMAKE_BUILD_TYPE`` String option. See the corresponding entry in the CMake manual. luabind-1.1.1/doc/building.rst000066400000000000000000000036561366245310300162410ustar00rootroot00000000000000Building luabind ================ Prerequisites ------------- Apart from Lua 5.1 or (recommended) 5.2, Luabind depends on a number of Boost libraries. It also depends on `CMake`_ to build the library and run the tests. .. _CMake: http://www.cmake.org/ Windows ------- If CMake has problems finding Lua, LUA_DIR needs to be set to point to a directory containing the Lua include directory and built libraries. The same applies to Boost and the BOOST_ROOT environment variable. Linux and other \*nix flavors ----------------------------- If your system already has Lua installed, it is very likely that the build system will automatically find it and just work. If you have Lua installed in a non-standard location, you may need to set ``LUA_DIR`` to point to the installation prefix. ``BOOST_ROOT`` can be set to a Boost installation directory. If left unset, the build system will try to use boost headers from the standard include path. Building and testing -------------------- Building the default variant of the library, which is a static release library, is simply done by invoking cmake in the luabind root directory and then running your native build tools on the generated files (e.g. make on Unix or nmake/msbuild ALL_BUILD.vcxproj for MSVC). .. note:: To build your application against the shared library variant, LUABIND_DYNAMIC_LINK needs to be defined to properly import symbols. To run the unit tests, invoke your build tool with the test target, e.g. ``make test`` on Unix or ``nmake test/msbuild RUN_TESTS.vcxproj`` for MSVC. This run the (previously built) unit tests in the current variant. A clean test run output should end with something like:: 100% tests passed, 0 tests failed out of 51 Total Test time (real) = 1.23 sec A failed run would end with something like:: 98% tests passed, 1 tests failed out of 51 Total Test time (real) = 1.23 sec The following tests FAILED: 1 - abstract_base (Failed) luabind-1.1.1/doc/changes.txt000066400000000000000000000114751366245310300160610ustar00rootroot00000000000000LUABIND 7.1 changes =================== * Applied patches from Evan Wies to support lua 5.1 * added a new assignment operator and a special value, luabind::nil, to set table entries to nil. LUABIND BETA 7 changes ====================== We have introduced a change that may break current code, nothing will break silently however. The change is that the previous way of writing virtual class wrappers was to have it contain an object that referred to the actual lua object. This would cause a dependency cycle and result in the object never being garbage collected until the whole lua state was closed. The new way is to use a newly introduced type called weak_ref, instead of the object. See docs for more info. Changes from beta6 ------------------ * renamed get_globals() and get_registry() to globals() and registry() * rewrote object and made a few changes: * moved iterators out of the class and removed begin/end/raw_begin/raw_end/array_begin/array_end. See updated docs for how to use the iterators. * removed array_iterator altogether * renamed pushvalue() to push() * removed set() * replaced the constructor that creates an object from a stack value (with better syntax) * moved out the member functions type(), at() and raw_at() and made them free functions. (type(), gettable(), settable(), rawget() and rawset()) * renamed lua_state() to interpreter() * object now supports nested indexing (with []-operator) as well as function calls directly on indexed values (i.e. globals(L)["my_fun"](10)). The indexing has also been made more efficient through the use of expression templates. * removed functor (use object with call_function() instead) * using boost-build, and has better support for building as a dll. The makefiles still works. * removed the option LUABIND_DONT_COPY_STRING, this means that luabind will not provide storage for name strings. i.e. the strings sent to module, namespace_ and class_ are expected to have global storage (it's no problem as long as you use string constants) wrappers ........ Wrapper classes now have to derive from wrap_base and they don't have to contain any references to the lua-part (this is done by the base class now). The overload of call_member() that previuosly took a weak_ref as first parameter is now a member function of the wrap_base class and no longer takes the self reference argument. Example: struct A { virtual ~A() {} virtual std::string f() { return "A:f()"; } }; struct A_wrap : A, wrap_base { virtual std::string f() { return call_member("f"); } static std::string default_f(A* p) { return p->A::f(); } }; The changes when registering the virtual functions is that you now have to register both the virtual function _and_ the default implementation of the function (for static dispatch). Like this: module(L) [ class_("A") .def(constructor<>()) .def("f", &A::f, &A_wrap::default_f) ] If you update your luabind version without changing the way you register virtual functions, it will still compile, but may give you runtime errors. With these changes adopt will work as expected on wrapped types (the weak reference will be transformed into a strong reference internally). These changes will also make dynamic function dispatch work from within lua (and not just from c++ into lua). policy placeholders ................... luabind now handles member functions in a more general way. The self reference that is passed as first parameter to member functions is now referred to using the _1 placeholder (instead of self). This means that the first argument to a member function is referred to with _2. additions ......... * added __newindex metatable entry on c++ classes * moved more code into cpp-files (hopefully reduces user compile time slightly) * the iterators are now true models of ForwardIterator * error messages when writing non-matching type to a property or attribute. * support for inner scopes * support for nil to holder_type conversion * wrappers for lua_resume() with the same syntax as call_function() (resume_function() and resume()) bugfixes ........ * bugs in the overload resolution could give internal errors in some cases. * def_readonly and def_readwrite will now return references if the type is not a primitive type. This will allow chained . operators. * object_cast() of uninitialized objects works * supports strings with extra nulls in them (not for member names though) * fixed reference leakage by reducing the amount of explicit resource management. * fixed bug where matchers for getters and setters did not propagate to derived classes. * fixed leak when using class wrappers. They had a reference cycle that wouldn't get collected (until the lua_State was closed). * lots of other fixes we can't remember luabind-1.1.1/doc/classes.rst000066400000000000000000000456521366245310300161030ustar00rootroot00000000000000.. _part-classes: Binding classes to Lua ====================== To register classes you use a class called ``class_``. Its name is supposed to resemble the C++ keyword, to make it look more intuitive. It has an overloaded member function ``def()`` that is used to register member functions, operators, constructors, enums and properties on the class. It will return its this-pointer, to let you register more members directly. Let's start with a simple example. Consider the following C++ class:: class testclass { public: testclass(const std::string& s): m_string(s) {} void print_string() { std::cout << m_string << "\n"; } private: std::string m_string; }; To register it with a Lua environment, write as follows (assuming you are using namespace luabind):: module(L) [ class_("testclass") .def(constructor()) .def("print_string", &testclass::print_string) ]; This will register the class with the name testclass and constructor that takes a string as argument and one member function with the name ``print_string``. .. code-block:: lua Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio > a = testclass('a string') > a:print_string() a string It is also possible to register free functions as member functions. The requirement on the function is that it takes a pointer, const pointer, reference or const reference to the class type as the first parameter. The rest of the parameters are the ones that are visible in Lua, while the object pointer is given as the first parameter. If we have the following C++ code:: struct A { int a; }; int plus(A* o, int v) { return o->a + v; } You can register ``plus()`` as if it was a member function of A like this:: class_("A") .def("plus", &plus) ``plus()`` can now be called as a member function on A with one parameter, int. If the object pointer parameter is const, the function will act as if it was a const member function (it can be called on const objects). Overloaded member functions --------------------------- When binding more than one overloads of a member function, or just binding one overload of an overloaded member function, you have to disambiguate the member function pointer you pass to ``def``. To do this, you can use an ordinary C-style cast, to cast it to the right overload. To do this, you have to know how to express member function types in C++, here's a short tutorial (for more info, refer to your favorite book on C++). The syntax for member function pointer follows: .. parsed-literal:: *return-value* (*class-name*::\*)(*arg1-type*, *arg2-type*, *...*) Here's an example illlustrating this:: struct A { void f(int); void f(int, int); }; :: class_() .def("f", (void(A::*)(int))&A::f) This selects the first overload of the function ``f`` to bind. The second overload is not bound. .. _sec-properties: Properties ---------- To register a global data member with a class is easily done. Consider the following class:: struct A { int a; }; This class is registered like this:: module(L) [ class_("A") .def_readwrite("a", &A::a) ]; This gives read and write access to the member variable ``A::a``. It is also possible to register attributes with read-only access:: module(L) [ class_("A") .def_readonly("a", &A::a) ]; When binding members that are a non-primitive type, the auto generated getter function will return a reference to it. This is to allow chained .-operators. For example, when having a struct containing another struct. Like this:: struct A { int m; }; struct B { A a; }; When binding ``B`` to lua, the following expression code should work: .. code-block:: lua b = B() b.a.m = 1 assert(b.a.m == 1) This requires the first lookup (on ``a``) to return a reference to ``A``, and not a copy. In that case, luabind will automatically use the dependency policy to make the return value dependent on the object in which it is stored. So, if the returned reference lives longer than all references to the object (b in this case) it will keep the object alive, to avoid being a dangling pointer. You can also register getter and setter functions and make them look as if they were a public data member. Consider the following class:: class A { public: void set_a(int x) { a = x; } int get_a() const { return a; } private: int a; }; It can be registered as if it had a public data member a like this:: class_("A") .property("a", &A::get_a, &A::set_a) This way the ``get_a()`` and ``set_a()`` functions will be called instead of just writing to the data member. If you want to make it read only you can just omit the last parameter. Please note that the get function **has to be const**, otherwise it won't compile. This seems to be a common source of errors. Enums ----- If your class contains enumerated constants (enums), you can register them as well to make them available in Lua. Note that they will not be type safe, all enums are integers in Lua, and all functions that takes an enum, will accept any integer. You register them like this:: module(L) [ class_("A") .enum_("constants") [ value("my_enum", 4), value("my_2nd_enum", 7), value("another_enum", 6) ] ]; In Lua they are accessed like any data member, except that they are read-only and reached on the class itself rather than on an instance of the class. .. code-block:: lua Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio > print(A.my_enum) 4 > print(A.another_enum) 6 Operators --------- To bind operators you have to include ````. The mechanism for registering operators on your class is pretty simple. You use a global name ``luabind::self`` to refer to the class itself and then you just write the operator expression inside the ``def()`` call. This class:: struct vec { vec operator+(int s); }; Is registered like this: .. parsed-literal:: module(L) [ class_("vec") .def(**self + int()**) ]; This will work regardless if your plus operator is defined inside your class or as a free function. If your operator is const (or, when defined as a free function, takes a const reference to the class itself) you have to use ``const_self`` instead of ``self``. Like this: .. parsed-literal:: module(L) [ class_("vec") .def(**const_self** + int()) ]; The operators supported are those available in Lua: .. parsed-literal:: + - \* / == < <= % This means, no in-place operators. Default implementations (described below) are provided for `==` and the special `__tostring` pseudo-operator. If any other operator is called, Luabind will trigger an error ("[const] class : no defined.", e.g. "class vec: no __div operator defined."). The equality operator (``==``) has a little hitch; it will not be called if the references are equal. This means that the ``==`` operator has to do pretty much what's it's expected to do. For Luabind's default `==` operator, two objects are equal only if they are both objects of Luabind-exported classes and have the same addresses, after casting both to a common base if neccessary. If they do not have a common base (and are not of the same type), they compare unequal. Lua does not support operators such as ``!=``, ``>`` or ``>=``. That's why you can only register the operators listed above. When you invoke one of the mentioned operators, lua will define it in terms of one of the available operators. In the above example the other operand type is instantiated by writing ``int()``. If the operand type is a complex type that cannot easily be instantiated you can wrap the type in a class called ``other<>``. For example: To register this class, we don't want to instantiate a string just to register the operator. :: struct vec { vec operator+(std::string); }; Instead we use the ``other<>`` wrapper like this: .. parsed-literal:: module(L) [ class_("vec") .def(self + **other()**) ]; To register an application (function call-) operator: .. parsed-literal:: module(L) [ class_("vec") .def( **self(int())** ) ]; There's one special operator. In Lua it's called ``__tostring``, it's not really an operator. It is used for converting objects to strings in a standard way in Lua. If you register this functionality, you will be able to use the lua standard function ``tostring()`` for converting your object to a string. To implement this operator in C++ you should supply an ``operator<<`` for std::ostream. Like this example: .. parsed-literal:: class number {}; std::ostream& operator<<(std::ostream&, number&); ... module(L) [ class_("number") .def(**tostring(self)**) ]; If you do not define a ``__tostring`` operator, Luabind supplies a default which result in strings of the form ``[const] object:
``, i.e. ``const`` is prepended if the object is const, ```` will be the string you supplied to ``class_`` (or a string derived from `std::type_info::name` for unnamed classes) and ``
`` will be the address of the C++ object. (Note that in multiple inheritance scenarios where the same object is pushed as multiple different base types, the addresses returned for the same most-derived object will differ). Nested scopes and static functions ---------------------------------- It is possible to add nested scopes to a class. This is useful when you need to wrap a nested class, or a static function. .. parsed-literal:: class_("foo") .def(constructor<>()) **.scope [ class_("nested"), def("f", &f) ]**; In this example, ``f`` will behave like a static member function of the class ``foo``, and the class ``nested`` will behave like a nested class of ``foo``. It's also possible to add namespaces to classes using the same syntax. Derived classes --------------- If you want to register classes that derives from other classes, you can specify a template parameter ``bases<>`` to the ``class_`` instantiation. The following hierarchy:: struct A {}; struct B : A {}; Would be registered like this:: module(L) [ class_("A"), class_("B") ]; If you have multiple inheritance you can specify more than one base. If B would also derive from a class C, it would be registered like this:: module(L) [ class_ >("B") ]; Note that you can omit ``bases<>`` when using single inheritance. .. note:: If you don't specify that classes derive from each other, luabind will not be able to implicitly cast pointers between the types. Smart pointers -------------- When registering a class you can tell luabind to hold all instances explicitly created in Lua in a specific smart pointer type, rather than the default raw pointer. This is done by passing an additional template parameter to ``class_``: .. parsed-literal:: class_(|...|) Where the requirements of ``P`` are: ======================== ======================================= Expression Returns ======================== ======================================= ``P(raw)`` ``get_pointer(p)`` Convertible to ``X*`` ======================== ======================================= where: * ``raw`` is of type ``X*`` * ``p`` is an instance of ``P`` ``get_pointer()`` overloads are provided for the smart pointers in Boost, and ``std::auto_ptr<>``. Should you need to provide your own overload, note that it is called unqualified and is expected to be found by *argument dependent lookup*. Thus it should be defined in the same namespace as the pointer type it operates on. For example: .. parsed-literal:: class_** >("X") .def(constructor<>()) Will cause luabind to hold any instance created on the Lua side in a ``boost::scoped_ptr``. Note that this doesn't mean **all** instances will be held by a ``boost::scoped_ptr``. If, for example, you register a function:: std::auto_ptr make_X(); the instance returned by that will be held in ``std::auto_ptr``. This is handled automatically for all smart pointers that implement a ``get_pointer()`` overload. .. important:: ``get_const_holder()`` has been removed. Automatic conversions between ``smart_ptr`` and ``smart_ptr`` no longer work. .. important:: ``__ok`` has been removed. Similar functionality can be implemented for specific pointer types by doing something along the lines of: .. parsed-literal:: bool is_non_null(std::auto_ptr const& p) { return p.get(); } |...| def("is_non_null", &is_non_null) When registering a hierarchy of classes, where all instances are to be held by a smart pointer, all the classes should have the baseclass' holder type. Like this: .. parsed-literal:: module(L) [ class_ >("base") .def(constructor<>()), class_** >("derived") .def(constructor<>()) ]; Internally, luabind will do the necessary conversions on the raw pointers, which are first extracted from the holder type. This means that for Luabind a ``smart_ptr`` is not related to a ``smart_ptr``, but ``derived*`` and ``base*`` are, as are ``smart_ptr`` and ``base*``. In other words, upcasting does not work for smart pointers as target types, but as source types. Additional support for shared_ptr and intrusive_ptr ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This limitation cannot be removed for all smart pointers in a generic way, but luabind has special support for * ``boost::shared_ptr`` in ``shared_ptr_converter.hpp`` * ``std::shared_ptr`` in ``std_shared_ptr_converter.hpp`` * ``boost::intrusive_ptr`` in ``intrusive_ptr_converter.hpp`` You should include the header(s) you need in the cpp files which register functions that accept the corresponding smart pointer types, to get automatic conversions from ``smart_ptr`` to ``smart_ptr``, whenever Luabind would convert ``X*`` to ``Y*``, removing the limitation mentioned above. However, the ``shared_ptr`` converters might not behave exactly as you would expect: 1. If the shared_ptr requested (from C++) has the exact same type as the one which is present in Lua (if any), then a copy will be made. 2. If the pointee type of the requested shared_ptr has a ``shared_from_this`` member (checked automatically at compile time), this will be used to obtain a ``shared_ptr``. Caveats: * If the object is not already held in a shared_ptr, behavior is undefined (probably a ``bad_weak_ptr`` exception will be thrown). * If the ``shared_from_this`` member is not a function with the right prototype (``ptr_t shared_from_this()`` with the expression :: shared_ptr(raw->shared_from_this(), raw) being valid, where ``raw`` is of type ``RequestedT*`` and points to the C++ object in Lua. 3. Otherwise, a new ``shared_ptr`` will be created from the raw pointer associated with the Lua object (even if it is not held in a ``shared_ptr``). It will have a deleter set that holds a strong reference to the Lua object, thus preventing it’s collection until the reference is released by invoking the deleter (i.e. by resetting or destroying the ``shared_ptr``) or until the assocciated ``lua_State`` is closed: then the ``shared_ptr`` becomes dangling. If such a ``shared_ptr`` is passed back to Lua, the original Lua object (userdata) will be passed instead, preventing the creation of more ``shared_ptr``\ s with this deleter. 1. is as you should have expected and 2. is special behavior introduced to avoid 3. when possible. If you cannot derive your (root) classes from ``enable_shared_from_this`` (which is the recommended way of providing a ``shared_from_this`` method) you must be careful not to close the ``lua_State`` when you still have a ``shared_ptr`` obtained by 3. There are three functions provided to support this (in namespace luabind):: bool is_state_unreferenced(lua_State* L); typedef void(*state_unreferenced_fun)(lua_State* L); void set_state_unreferenced_callback(lua_State* L, state_unreferenced_fun cb); state_unreferenced_fun get_state_unreferenced_callback(lua_State* L); ``is_state_unreferenced`` will return ``false`` if closing ``L`` would make existing ``shared_ptrs`` dangling and ``true`` if it safe (in this respect) to call ``lua_close(L)``. The ``cb`` argument passed to ``set_state_unreferenced_callback`` will be called whenever the return value of ``is_state_unreferenced(L)`` would change from ``false`` to ``true``. ``get_state_unreferenced_callback`` returns the current ``state_unreferenced_fun`` for ``L``. A typical use of this functions would be to replace :: lua_close(L); with :: if (luabind::is_state_unreferenced(L)) lua_close(L); else luabind::set_state_unreferenced_callback(L, &lua_close); (``lua_close`` happens to be a valid ``state_unreferenced_fun``.) Unnamed classes --------------- You can register unnamed classes by not passing a name to ``class_``:: class_() This does not export the class object itself to Lua, meaning that constructors cannot be called and enums are only accessible via objects of this class' type. This is useful e.g. for registering multiple instantiations of a class template, and construct a matching instance using a factory function, like boost::make_shared of for hiding intermediate classes in inheritance hierarchies. .. _sec-split-cls-registration: Splitting class registrations ----------------------------- In some situations it may be desirable to split a registration of a class across different compilation units. Partly to save rebuild time when changing in one part of the binding, and in some cases compiler limits may force you to split it. To do this is very simple. Consider the following sample code:: void register_part1(class_& x) { x.def(/*...*/); } void register_part2(class_& x) { x.def(/*...*/); } void register_(lua_State* L) { class_ 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 compilation units. To separate the module registration and the classes to be registered, see :ref:`part-split-registration`.luabind-1.1.1/doc/conf.py000066400000000000000000000200501366245310300151740ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Luabind documentation build configuration file, created by # sphinx-quickstart on Thu Aug 08 22:35:23 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Luabind' copyright = u'2005 Rasterbar Software; 2013 Christian Neumüller' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.9' # The full version, including alpha/beta/rc tags. with open('git_version') as f: release = f.readline() # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build', 'policies', 'version.rst'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False primary_domain = 'cpp' highlight_language = 'c++' rst_epilog = """ .. |...| unicode:: U+02026 """ # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'pyramid' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. html_short_title = 'Luabind' # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Luabinddoc' html_use_modindex = False html_use_index = False # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Luabind.tex', u'Luabind Documentation', u'Daniel Wallin, Arvid Norberg', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'luabind', u'Luabind Documentation', [u'Daniel Wallin, Arvid Norberg'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Luabind', u'Luabind Documentation', u'Daniel Wallin, Arvid Norberg', 'Luabind', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False luabind-1.1.1/doc/errors.rst000066400000000000000000000154211366245310300157510ustar00rootroot00000000000000Error Handling ============== .. _sec-pcall-errorfunc: pcall errorfunc --------------- As mentioned in the `Lua documentation`_, it is possible to pass an error handler function to ``lua_pcall()``. Luabind makes use of ``lua_pcall()`` internally when calling member functions and free functions. It is possible to set the error handler function that Luabind will use globally:: typedef int(*pcall_callback_fun)(lua_State*); void set_pcall_callback(pcall_callback_fun fn); This is primarily useful for adding more information to the error message returned by a failed protected call. For more information on how to use the pcall_callback function, see ``errfunc`` under the `pcall section of the lua manual`_. For more information on how to retrieve debugging information from lua, see `the debug section of the lua manual`_. The message returned by the ``pcall_callback`` is accessable as the top lua value on the stack. For example, if you would like to access it as a luabind object, you could do like this:: catch(error& e) { object error_msg(from_stack(e.state(), -1)); std::cout << error_msg << std::endl; } .. _Lua documentation: http://www.lua.org/manual/5.0/manual.html .. _`pcall section of the lua manual`: http://www.lua.org/manual/5.0/manual.html#3.15 .. _`the debug section of the lua manual`: http://www.lua.org/manual/5.0/manual.html#4 file and line numbers --------------------- If you want to add file name and line number to the error messages generated by luabind you can define your own `pcall errorfunc`_. You may want to modify this callback to better suit your needs, but the basic functionality could be implemented like this:: int add_file_and_line(lua_State* L) { lua_Debug d; lua_getstack(L, 1, &d); lua_getinfo(L, "Sln", &d); std::string err = lua_tostring(L, -1); lua_pop(L, 1); std::stringstream msg; msg << d.short_src << ":" << d.currentline; if (d.name != 0) { msg << "(" << d.namewhat << " " << d.name << ")"; } msg << " " << err; lua_pushstring(L, msg.str().c_str()); return 1; } For more information about what kind of information you can add to the error message, see `the debug section of the lua manual`_. Note that the callback set by ``set_pcall_callback()`` will only be used when luabind executes lua code. Anytime when you call ``lua_pcall`` yourself, you have to supply your function if you want error messages translated. .. _sec-lua-panic: lua panic --------- When lua encounters a fatal error caused by a bug from the C/C++ side, it will call its internal panic function. This can happen, for example, when you call ``lua_gettable`` on a value that isn't a table. If you do the same thing from within lua, it will of course just fail with an error message. The default panic function will ``exit()`` the application. If you want to handle this case without terminating your application, you can define your own panic function using ``lua_atpanic``. The best way to continue from the panic function is to make sure lua is compiled as C++ and throw an exception from the panic function. Throwing an exception instead of using ``setjmp`` and ``longjmp`` will make sure the stack is correctly unwound. When the panic function is called, the lua state is invalid, and the only allowed operation on it is to close it. For more information, see the `lua manual section 3.19`_. .. _`lua manual section 3.19`: http://www.lua.org/manual/5.0/manual.html#3.19 structured exceptions (MSVC) ---------------------------- Since lua is generally built as a C library, any callbacks called from lua cannot under any circumstance throw an exception. Because of that, luabind has to catch all exceptions and translate them into proper lua errors (by calling ``lua_error()``). This means we have a ``catch(...) {}`` in there. In Visual Studio, ``catch (...)`` will not only catch C++ exceptions, it will also catch structured exceptions, such as segmentation fault. This means that if your function, that gets called from luabind, makes an invalid memory adressing, you won't notice it. All that will happen is that lua will return an error message saying "unknown exception". To remedy this, you can create your own *exception translator*:: void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*) { throw; } #ifdef _MSC_VER ::_set_se_translator(straight_to_debugger); #endif This will make structured exceptions, like segmentation fault, to actually get caught by the debugger. Error messages -------------- These are the error messages that can be generated by luabind, with a more in-depth explanation. - .. parsed-literal:: the attribute '*class-name.attribute-name*' is read only There is no data member named *attribute-name* in the class *class-name*, or there's no setter-function registered on that property name. See the :ref:`sec-properties` section. - .. parsed-literal:: the attribute '*class-name.attribute-name*' is of type: (*class-name*) and does not match (*class_name*) This error is generated if you try to assign an attribute with a value of a type that cannot be converted to the attributes type. - .. parsed-literal:: *class-name()* threw an exception, *class-name:function-name()* threw an exception The class' constructor or member function threw an unknown exception. Known exceptions are const char*, std::exception. See the :ref:`part-exceptions` section. - .. parsed-literal:: no overload of '*class-name:function-name*' matched the arguments (*parameter-types*) no match for function call '*function-name*' with the parameters (*parameter-types*) no constructor of *class-name* matched the arguments (*parameter-types*) no operator *operator-name* matched the arguments (*parameter-types*) No function/operator with the given name takes the parameters you gave it. You have either misspelled the function name, or given it incorrect parameters. This error is followed by a list of possible candidate functions to help you figure out what parameter has the wrong type. If the candidate list is empty there's no function at all with that name. See the signature matching section. - .. parsed-literal:: call of overloaded '*class-name:function-name*(*parameter-types*)' is ambiguous ambiguous match for function call '*function-name*' with the parameters (*parameter-types*) call of overloaded constructor '*class-name*(*parameter-types*)' is ambiguous call of overloaded operator *operator-name* (*parameter-types*) is ambiguous This means that the function/operator you are trying to call has at least one other overload that matches the arguments just as good as the first overload. - .. parsed-literal:: cannot derive from C++ class '*class-name*'. It does not have a wrapped type. luabind-1.1.1/doc/exceptions.rst000066400000000000000000000105371366245310300166210ustar00rootroot00000000000000.. _part-exceptions: Exceptions ========== If any of the functions you register throws an exception when called, that exception will be caught by luabind and converted to an error string and ``lua_error()`` will be invoked. If the exception is a ``std::exception`` or a ``const char*`` the string that is pushed on the Lua stack, as error message, will be the string returned by ``std::exception::what()`` or the string itself respectively. If the exception is unknown, a generic string saying that the function threw an exception will be pushed. If you have an exception type that isn't derived from ``std::exception``, or you wish to change the error message from the default result of ``what()``, it is possible to register custom exception handlers:: struct my_exception {}; void translate_my_exception(lua_State* L, my_exception const&) { lua_pushstring(L, "my_exception"); } … luabind::register_exception_handler(&translate_my_exception); ``translate_my_exception()`` will be called by luabind whenever a ``my_exception`` is caught. ``lua_error()`` will be called after the handler function returns, so it is expected that the function will push an error string on the stack. Any function that invokes Lua code may throw ``luabind::error``. This exception means that a Lua run-time error occurred. The error message is found on top of the Lua stack. The reason why the exception doesn't contain the error string itself is because it would then require heap allocation which may fail. If an exception class throws an exception while it is being thrown itself, the application will be terminated. Error's synopsis is:: class error : public std::exception { public: error(lua_State*); lua_State* state() const throw(); virtual const char* what() const throw(); }; The state function returns a pointer to the Lua state in which the error was thrown. This pointer may be invalid if you catch this exception after the lua state is destructed. If the Lua state is valid you can use it to retrieve the error message from the top of the Lua stack. An example of where the Lua state pointer may point to an invalid state follows:: struct lua_state { lua_state(lua_State* L): m_L(L) {} ~lua_state() { lua_close(m_L); } operator lua_State*() { return m_L; } lua_State* m_L; }; int main() { try { lua_state L = luaL_newstate(); /* ... */ } catch(luabind::error& e) { lua_State* L = e.state(); // L will now point to the destructed // Lua state and be invalid /* ... */ } } There's another exception that luabind may throw: ``luabind::cast_failed``, this exception is thrown from ``call_function<>`` or ``call_member<>``. It means that the return value from the Lua function couldn't be converted to a C++ value. It is also thrown from ``object_cast<>`` if the cast cannot be made. The synopsis for ``luabind::cast_failed`` is:: class cast_failed : public std::exception { public: cast_failed(lua_State*); lua_State* state() const throw(); LUABIND_TYPE_INFO info() const throw(); virtual const char* what() const throw(); }; Again, the state member function returns a pointer to the Lua state where the error occurred. See the example above to see where this pointer may be invalid. The info member function returns the user defined ``LUABIND_TYPE_INFO``, which defaults to a ``const std::type_info*``. This type info describes the type that we tried to cast a Lua value to. If you have defined ``LUABIND_NO_EXCEPTIONS`` none of these exceptions will be thrown, instead you can set two callback functions that are called instead. These two functions are only defined if ``LUABIND_NO_EXCEPTIONS`` are defined. :: luabind::set_error_callback(void(*)(lua_State*)) The function you set will be called when a runtime-error occur in Lua code. You can find an error message on top of the Lua stack. This function is not expected to return, if it does luabind will call ``std::terminate()``. :: luabind::set_cast_failed_callback(void(*)(lua_State*, LUABIND_TYPE_INFO)) The function you set is called instead of throwing ``cast_failed``. This function is not expected to return, if it does luabind will call ``std::terminate()``.luabind-1.1.1/doc/faq.rst000066400000000000000000000100421366245310300151760ustar00rootroot00000000000000FAQ === What's up with __cdecl and __stdcall? If you're having problem with functions that cannot be converted from ``void (__stdcall *)(int,int)`` to ``void (__cdecl*)(int,int)``. You can change the project settings to make the compiler generate functions with __cdecl calling conventions. This is a problem in developer studio. What's wrong with functions taking variable number of arguments? You cannot register a function with ellipses in its signature. Since ellipses don't preserve type safety, those should be avoided anyway. Internal structure overflow in VC If you, in visual studio, get fatal error C1204: compiler limit : internal structure overflow. You should try to split that compilation unit up in smaller ones. See :ref:`part-split-registration` and :ref:`sec-split-cls-registration`. What's wrong with precompiled headers in VC? Visual Studio doesn't like anonymous namespaces in its precompiled headers. If you encounter this problem you can disable precompiled headers for the compilation unit (cpp-file) that uses luabind. error C1076: compiler limit - internal heap limit reached in VC In visual studio you will probably hit this error. To fix it you have to increase the internal heap with a command-line option. We managed to compile the test suit with /Zm300, but you may need a larger heap then that. error C1055: compiler limit \: out of keys in VC It seems that this error occurs when too many assert() are used in a program, or more specifically, the __LINE__ macro. It seems to be fixed by changing /ZI (Program database for edit and continue) to /Zi (Program database). How come my executable is huge? If you're compiling in debug mode, you will probably have a lot of debug-info and symbols (luabind consists of a lot of functions). Also, if built in debug mode, no optimizations were applied, luabind relies on that the compiler is able to inline functions. If you built in release mode, try running strip on your executable to remove export-symbols, this will trim down the size. Our tests suggests that cygwin's gcc produces much bigger executables compared to gcc on other platforms and other compilers. .. HUH?! // check the magic number that identifies luabind's functions Can I register class templates with luabind? Yes you can, but you can only register explicit instantiations of the class. Because there's no Lua counterpart to C++ templates. For example, you can register an explicit instantiation of std::vector<> like this:: module(L) [ class_ >("vector") .def(constructor) .def("push_back", &std::vector::push_back) ]; .. Again, irrelevant to docs: Note that the space between the two > is required by C++. Do I have to register destructors for my classes? No, the destructor of a class is always called by luabind when an object is collected. Note that Lua has to own the object to collect it. If you pass it to C++ and gives up ownership (with adopt policy) it will no longer be owned by Lua, and not collected. If you have a class hierarchy, you should make the destructor virtual if you want to be sure that the correct destructor is called (this apply to C++ in general). .. And again, the above is irrelevant to docs. This isn't a general C++ FAQ. But it saves us support questions. Fatal Error C1063 compiler limit \: compiler stack overflow in VC VC6.5 chokes on warnings, if you are getting alot of warnings from your code try suppressing them with a pragma directive, this should solve the problem. Crashes when linking against luabind as a dll in Windows When you build luabind, Lua and you project, make sure you link against the runtime dynamically (as a dll). I cannot register a function with a non-const parameter This is because there is no way to get a reference to a Lua value. Have a look at :ref:`policy-out_value` and :ref:`policy-pure_out_value` policies.luabind-1.1.1/doc/functions.rst000066400000000000000000000145121366245310300164450ustar00rootroot00000000000000.. _part-functions: Binding functions to Lua ======================== To bind functions to Lua you use the function ``luabind::def()``. It has the following synopsis:: template 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 :ref:`part-policies` section. An example usage could be if you want to register the function ``float std::sin(float)``:: module(L) [ def("sin", &std::sin) ]; Overloaded functions -------------------- If you have more than one function with the same name, and want to register them in Lua, you have to explicitly give the signature. This is to let C++ know which function you refer to. For example, if you have two functions, ``int f(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 there can match your functions' signatures. It will handle implicit typecasts between derived classes, and it will prefer matches with the least number of implicit casts. In a function call, if the function is overloaded and there's no overload that match the parameters better than the other, you have an ambiguity. This will spawn a run-time error, stating that the function call is ambiguous. A simple example of this is to register one function that takes an int and one that takes a float. Since Lua doesn't distinguish between floats and integers, both will always match. Since all overloads are tested, it will always find the best match (not the first match). This also means that it can handle situations where the only difference in the signature is that one member function is const and the other isn't. .. sidebar:: Ownership transfer To correctly handle ownership transfer, create_a() would need an adopt return value policy. More on this in the :ref:`part-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: .. code-block:: lua 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()`` or an ``object``. :: template Ret call_function(lua_State* L, const char* name, ...) template Ret call_function(object const& obj, ...) There are two overloads of the ``call_function`` function, one that calls a function given its name, and one that takes an object that should be a Lua value 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 Lua function. This function call may throw ``luabind::error`` if the function call fails. The return value isn't actually Ret (the template parameter), but a proxy object that will do the function call. This enables you to give policies to the call. You do this with the operator[]. You give the policies within the brackets, like this:: int ret = call_function( 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 `Boost.Ref`__. __ http://www.boost.org/doc/html/ref.html Like this:: int ret = call_function(L, "fun", boost::ref(val)); If you want to use a custom error handler for the function call, see ``set_pcall_callback`` under :ref:`sec-pcall-errorfunc`. Using Lua threads ----------------- To start a Lua thread, you have to call ``lua_resume()``, this means that you cannot use the previous function ``call_function()`` to start a thread. You have to use :: template Ret resume_function(lua_State* L, const char* name, ...) template Ret resume_function(object const& obj, ...) and :: template Ret resume(lua_State* L, ...) The first time you start the thread, you have to give it a function to execute. i.e. you have to use ``resume_function``, when the Lua function yields, it will return the first value passed in to ``lua_yield()``. When you want to continue the execution, you just call ``resume()`` on your ``lua_State``, since it's already executing a function, you don't pass it one. The parameters to ``resume()`` will be returned by ``yield()`` on the Lua side. For yielding C++-functions (without the support of passing data back and forth between the Lua side and the c++ side), you can use the :ref:`policy-yield` policy. With the overload of ``resume_function`` that takes an :ref:`part-object`, it is important that the object was constructed with the thread as its ``lua_State*``. Like this: .. parsed-literal:: lua_State* thread = lua_newthread(L); object fun = get_global(**thread**)["my_thread_fun"]; resume_function(fun); Binding function objects with explicit signatures ------------------------------------------------- Using ``luabind::tag_function<>`` it is possible to export function objects from which luabind can't automatically deduce a signature. This can be used to slightly alter the signature of a bound function, or even to bind stateful function objects. Synopsis: .. parsed-literal:: template *implementation-defined* tag_function(F f); Where ``Signature`` is a function type describing the signature of ``F``. It can be used like this:: int f(int x); // alter the signature so that the return value is ignored def("f", tag_function(f)); struct plus { plus(int x) : x(x) {} int operator()(int y) const { return x + y; } }; // bind a stateful function object def("plus3", tag_function(plus(3))); luabind-1.1.1/doc/git_version.in000066400000000000000000000000171366245310300165560ustar00rootroot00000000000000@DOCS_VERSION@ luabind-1.1.1/doc/impl-notes.rst000066400000000000000000000033631366245310300165260ustar00rootroot00000000000000Implementation notes ==================== The classes and objects are implemented as user data in Lua. To make sure that the user data really is the internal structure it is supposed to be, we tag their metatables. Previously a boolean at a string key was used, making it relatively easy for the malevolent user to fool Luabind and crash the application. However, this has been replaced with a light userdata key that should be quite impossible to imitate. In the Lua registry, luabind kept an entry called ``"__luabind_classes"``. This string key is now also replaced with a light userdata one. In the global table, a variable called ``super`` is used every time a constructor in a lua-class is called. This is to make it easy for that constructor to call its base class' constructor. So, if you have a global variable named super it may be overwritten. This is probably not the best solution, and this restriction may be removed in the future. .. note:: Deprecated ``super()`` has been deprecated since version 0.8 in favor of directly invoking the base class' ``__init()`` function:: function Derived:__init() Base.__init(self) end The detail namespace and undocumented features ---------------------------------------------- Inside the luabind namespace, there’s another namespace called ``detail``. Everything cotained therein should not be used by user code and is subject to change or vanish even between patch versions. There also exist no explicit tests or documentation for this namespace’s contents. Classes and functions which reside directly in the ``luabind`` namespace but are not documented should also rather not be used. However, if you have to depend on undocumented features, these are still better than the ``detail`` ones. luabind-1.1.1/doc/index.html000066400000000000000000000050051366245310300156750ustar00rootroot00000000000000 luabind

luabind logo

download documentation mailing list the sourceforge page

Luabind is a library that helps you create bindings between C++ and lua. It has the ability to expose functions and classes, written in C++, to lua. It will also supply the functionality to define classes in lua and let them derive from other lua classes or C++ classes. Lua classes can override virtual functions from their C++ baseclasses. It is written towards lua 5.0, and does not work with lua 4.

It is implemented utilizing template meta programming. That means that you don't need an extra preprocess pass to compile your project (it is done by the compiler). 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.

luabind is hosted by sourceforge.
SourceForge.net Logo
Valid HTML 4.01! Valid CSS!

luabind-1.1.1/doc/index.rst000066400000000000000000000016531366245310300155460ustar00rootroot00000000000000Luabind |version| documentation =============================== This is the documentation for Luabind |release|. Luabind is a library that helps you create bindings between C++ and Lua. It has the ability to expose functions and classes, written in C++, to Lua. It will also supply the functionality to define classes in Lua and let them derive from other Lua classes or C++ classes. Lua classes can override virtual functions from their C++ base classes. It is written towards Lua 5.2 but should also work with 5.1. The old official homepage can be found at http://www.rasterbar.com/products/luabind.html. Contents: .. toctree:: :maxdepth: 2 intro building basic-usage scopes functions classes userdefined-converters object lua-classes exceptions policies split-registration errors build-options impl-notes faq issues acknowledgments Searchpage ========== * :ref:`search` luabind-1.1.1/doc/intro.rst000066400000000000000000000051171366245310300155710ustar00rootroot00000000000000Introduction ============ Luabind is a library that helps you create bindings between C++ and Lua. It has the ability to expose functions and classes, written in C++, to Lua. It will also supply the functionality to define classes in Lua and let them derive from other Lua classes or C++ classes. Lua classes can override virtual functions from their C++ base classes. It is written towards Lua 5.2 but should also work with 5.1. It is implemented utilizing template meta programming. That means that you don't need an extra preprocess pass to compile your project (it is done by the compiler). 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 let us 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. Additionally, this fork’s `github issue tracker`_ can also be used for bug reports, feature requests and questions. .. _`luabind mailing list`: https://lists.sourceforge.net/lists/listinfo/luabind-user .. _MIT license: http://www.opensource.org/licenses/mit-license.php .. _Boost: http://www.boost.org .. _github issue tracker: https://github.com/Oberon00/luabind/issues Features ======== Luabind supports: - Overloaded free functions - C++ classes in Lua - Overloaded member functions - Operators - Properties - Enums (also C++11 ``enum class`` if available) - 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 is currently tested regularly with * Microsoft Visual C++ 11 (2012) x32 and x64 * gcc 4.8 x64 (with and without -std=c++11) * Clang 3.2 x64 (with and without -std=c++11) It should work with any compiler conformant with C++03. However, probably only versions of the above threecompilers will work out of the box with the provided CMake build files. Please report any issues you have to the `github issue tracker`_. luabind-1.1.1/doc/issues.rst000066400000000000000000000010621366245310300157440ustar00rootroot00000000000000Known issues ============ - You cannot use strings with extra nulls in them as member names that refers to C++ members. - If one class registers two functions with the same name and the same signature, there's currently no error. The last registered function will be the one that's used. - In VC7, classes can not be called test. - If you register a function and later rename it, error messages will use the original function name. - luabind does not support class hierarchies with virtual inheritance. Casts are done with static pointer offsets. luabind-1.1.1/doc/lua-classes.rst000066400000000000000000000242561366245310300166570ustar00rootroot00000000000000.. highlight:: lua Defining classes in Lua ======================= In addition to binding C++ functions and classes with Lua, luabind also provide an OO-system in Lua. :: class 'lua_testclass' function lua_testclass:__init(name) self.name = name end function lua_testclass:print() print(self.name) end a = lua_testclass('example') a:print() Inheritance can be used between lua-classes:: class 'derived' (lua_testclass) function derived:__init() lua_testclass.__init(self, 'derived name') end function derived:print() print('Derived:print() -> ') lua_testclass.print(self) end The base class is initialized explicitly by calling its ``__init()`` function. As you can see in this example, you can call the base class member functions. You can find all member functions in the base class, but you will have to give the this-pointer (``self``) as first argument. Deriving in lua --------------- It is also possible to derive Lua classes from C++ classes, and override virtual functions with Lua functions. To do this we have to create a wrapper class for our C++ base class. This is the class that will hold the Lua object when we instantiate a Lua class. .. code-block:: c++ class base { public: base(const char* s) { std::cout << s << "\n"; } virtual void f(int a) { std::cout << "f(" << a << ")\n"; } }; struct base_wrapper : base, luabind::wrap_base { base_wrapper(const char* s) : base(s) {} virtual void f(int a) { call("f", a); } static void default_f(base* ptr, int a) { return ptr->base::f(a); } }; // ... module(L) [ class_("base") .def(constructor()) .def("f", &base::f, &base_wrapper::default_f) ]; .. Important:: Since MSVC6.5 doesn't support explicit template parameters to member functions, instead of using the member function ``call()`` you call a free function ``call_member()`` and pass the this-pointer as first parameter. Note that if you have both base classes and a base class wrapper, you must give both bases and the base class wrapper type as template parameter to ``class_`` (as done in the example above). The order in which you specify them is not important. You must also register both the static version and the virtual version of the function from the wrapper, this is necessary in order to allow luabind to use both dynamic and static dispatch when calling the function. .. Important:: It is extremely important that the signatures of the static (default) function is identical to the virtual function. The fact that one of them is a free function and the other a member function doesn't matter, but the parameters as seen from lua must match. It would not have worked if the static function took a ``base_wrapper*`` as its first argument, since the virtual function takes a ``base*`` as its first argument (its this pointer). There's currently no check in luabind to make sure the signatures match. If we didn't have a class wrapper, it would not be possible to pass a Lua class back to C++. Since the entry points of the virtual functions would still point to the C++ base class, and not to the functions defined in Lua. That's why we need one function that calls the base class' real function (used if the lua class doesn't redefine it) and one virtual function that dispatches the call into luabind, to allow it to select if a Lua function should be called, or if the original function should be called. If you don't intend to derive from a C++ class, or if it doesn't have any virtual member functions, you can register it without a class wrapper. You don't need to have a class wrapper in order to derive from a class, but if it has virtual functions you may have silent errors. .. Unnecessary? The rule of thumb is: If your class has virtual functions, create a wrapper type, if it doesn't don't create a wrapper type. The wrappers must derive from ``luabind::wrap_base``, it contains a Lua reference that will hold the Lua instance of the object to make it possible to dispatch virtual function calls into Lua. This is done through an overloaded member function: .. code-block:: c++ template Ret call(char const* name, ...) Its used in a similar way as ``call_function``, with the exception that it doesn't take a ``lua_State`` pointer, and the name is a member function in the Lua class. .. warning:: The current implementation of ``call_member`` is not able to distinguish const member functions from non-const. If you have a situation where you have an overloaded virtual function where the only difference in their signatures is their constness, the wrong overload will be called by ``call_member``. This is rarely the case though. .. note:: You can also override virtual member functions per instance which often makes it unnecessary to derive a new class in Lua. Instead of e.g. :: class "D" (B) function D:__init() B.__init(self) end function D:virtual_function() ... end you may be able to get around with :: b = B() function b:virtual_function() ... end .. _sec-objid: Object identity ~~~~~~~~~~~~~~~ When a pointer or reference to a registered class with a wrapper is passed to Lua, luabind will query for it's dynamic type. If the dynamic type inherits from ``wrap_base``, object identity is preserved. .. code-block:: c++ struct A { .. }; struct A_wrap : A, wrap_base { .. }; A* f(A* ptr) { return ptr; } module(L) [ class_("A"), def("f", &f) ]; :: > class 'B' (A) > x = B() > assert(x == f(x)) -- object identity is preserved when object is -- passed through C++ This functionality relies on RTTI being enabled (that ``LUABIND_NO_RTTI`` is not defined). Overloading operators --------------------- You can overload most operators in Lua for your classes. You do this by simply declaring a member function with the same name as an operator (the name of the metamethods in Lua). The operators you can overload are: - ``__add`` - ``__sub`` - ``__mul`` - ``__div`` - ``__pow`` - ``__lt`` - ``__le`` - ``__eq`` - ``__call`` - ``__unm`` - ``__tostring`` - ``__len`` ``__tostring`` isn't really an operator, but it's the metamethod that is called by the standard library's ``tostring()`` function. There's one strange behavior regarding binary operators. You are not guaranteed that the self pointer you get actually refers to an instance of your class. This is because Lua doesn't distinguish the two cases where you get the other operand as left hand value or right hand value. Consider the following examples:: class 'my_class' function my_class:__init(v) self.val = v end function my_class:__sub(v) return my_class(self.val - v.val) end function my_class:__tostring() return self.val end This will work well as long as you only subtracts instances of my_class with each other. But If you want to be able to subtract ordinary numbers from your class too, you have to manually check the type of both operands, including the self object. :: function my_class:__sub(v) if (type(self) == 'number') then return my_class(self - v.val) elseif (type(v) == 'number') then return my_class(self.val - v) else -- assume both operands are instances of my_class return my_class(self.val - v.val) end end The reason why ``__sub`` is used as an example is because subtraction is not commutative (the order of the operands matters). That's why luabind cannot change order of the operands to make the self reference always refer to the actual class instance. If you have two different Lua classes with an overloaded operator, the operator of the right hand side type will be called. If the other operand is a C++ class with the same operator overloaded, it will be prioritized over the Lua class' operator. If none of the C++ overloads matches, the Lua class operator will be called. Finalizers ---------- If an object needs to perform actions when it's collected we provide a ``__finalize`` function that can be overridden in lua-classes. The ``__finalize`` functions will be called on all classes in the inheritance chain, starting with the most derived type. :: ... function lua_testclass:__finalize() -- called when the an object is collected end Slicing ------- If your lua C++ classes don't have wrappers (see `Deriving in lua`_) and you derive from them in lua, they may be sliced. Meaning, if an object is passed into C++ as a pointer to its base class, the lua part will be separated from the C++ base part. This means that if you call virtual functions on that C++ object, they will not be dispatched to the lua class. It also means that if you adopt the object, the lua part will be garbage collected. :: +--------------------+ | C++ object | <- ownership of this part is transferred | | to c++ when adopted +--------------------+ | lua class instance | <- this part is garbage collected when | and lua members | instance is adopted, since it cannot +--------------------+ be held by c++. The problem can be illustrated by this example: .. code-block:: c++ struct A {}; A* filter_a(A* a) { return a; } void adopt_a(A* a) { delete a; } .. code-block:: c++ using namespace luabind; module(L) [ class_("A"), def("filter_a", &filter_a), def("adopt_a", &adopt_a, adopt(_1)) ] In lua:: a = A() b = filter_a(a) adopt_a(b) In this example, lua cannot know that ``b`` actually is the same object as ``a``, and it will therefore consider the object to be owned by the C++ side. When the ``b`` pointer then is adopted, a runtime error will be raised because an object not owned by lua is being adopted to C++. If you have a wrapper for your class, none of this will happen, see `Object identity`_. luabind-1.1.1/doc/luabind-logo-label.ps000066400000000000000000000113451366245310300177010ustar00rootroot00000000000000%!PS-Adobe-2.0 EPSF-2.0 %%Title: Lua logo %%Creator: lua@tecgraf.puc-rio.br %%CreationDate: Wed Nov 29 19:04:04 EDT 2000 %%BoundingBox: -45 0 1035 1080 %%Pages: 1 %%EndComments %%EndProlog %------------------------------------------------------------------------------ % % Copyright (C) 1998-2000. All rights reserved. % Graphic design by Alexandre Nakonechny (nako@openlink.com.br). % PostScript programming by the Lua team (lua@tecgraf.puc-rio.br). % % Permission is hereby granted, without written agreement and without license % or royalty fees, to use, copy, and distribute this logo for any purpose, % including commercial applications, subject to the following conditions: % % * The origin of this logo must not be misrepresented; you must not % claim that you drew the original logo. We recommend that you give credit % to the graphics designer in all printed matter that includes the logo. % % * The only modification you can make is to adapt the orbiting text to % your product name. % % * The logo can be used in any scale as long as the relative proportions % of its elements are maintained. % %------------------------------------------------------------------------------ /LABEL (luabind) def %-- DO NOT CHANGE ANYTHING BELOW THIS LINE ------------------------------------ /PLANETCOLOR {0 0 0.5 setrgbcolor} bind def /HOLECOLOR {1.0 setgray} bind def /ORBITCOLOR {0.5 setgray} bind def /LOGOFONT {/Helvetica 0.90} def /LABELFONT {/Helvetica 0.36} def %------------------------------------------------------------------------------ /MOONCOLOR {PLANETCOLOR} bind def /LOGOCOLOR {HOLECOLOR} bind def /LABELCOLOR {ORBITCOLOR} bind def /LABELANGLE 125 def /LOGO (Lua) def /DASHANGLE 10 def /HALFDASHANGLE DASHANGLE 2 div def % moon radius. planet radius is 1. /r 1 2 sqrt 2 div sub def /D {0 360 arc fill} bind def /F {exch findfont exch scalefont setfont} bind def % place it nicely on the paper /RESOLUTION 1024 def RESOLUTION 2 div dup translate RESOLUTION 2 div 2 sqrt div dup scale %-------------------------------------------------------------------- planet -- PLANETCOLOR 0 0 1 D %---------------------------------------------------------------------- hole -- HOLECOLOR 1 2 r mul sub dup r D %---------------------------------------------------------------------- moon -- MOONCOLOR 1 1 r D %---------------------------------------------------------------------- logo -- LOGOCOLOR LOGOFONT F LOGO stringwidth pop 2 div neg -0.5 moveto LOGO show %------------------------------------------------------------------------------ % based on code from Blue Book Program 10, on pages 167--169 % available at ftp://ftp.adobe.com/pub/adobe/displaypostscript/bluebook.shar % str ptsize centerangle radius outsidecircletext -- /outsidecircletext { circtextdict begin /radius exch def /centerangle exch def /ptsize exch def /str exch def gsave str radius ptsize findhalfangle centerangle add rotate str { /charcode exch def ( ) dup 0 charcode put outsideplacechar } forall grestore end } def % string radius ptsize findhalfangle halfangle /findhalfangle { 4 div add exch stringwidth pop 2 div exch 2 mul 3.1415926535 mul div 360 mul } def /circtextdict 16 dict def circtextdict begin /outsideplacechar { /char exch def /halfangle char radius ptsize findhalfangle def gsave halfangle neg rotate radius 0 translate -90 rotate char stringwidth pop 2 div neg 0 moveto char show grestore halfangle 2 mul neg rotate } def end %--------------------------------------------------------------------- label -- LABELFONT F /LABELSIZE LABELFONT exch pop def /LABELRADIUS LABELSIZE 3 div 1 r add sub neg 1.02 mul def /HALFANGLE LABEL LABELRADIUS LABELSIZE findhalfangle HALFDASHANGLE div ceiling HALFDASHANGLE mul def /LABELANGLE 60 LABELANGLE HALFANGLE sub lt { HALFANGLE HALFANGLE DASHANGLE div floor DASHANGLE mul eq {LABELANGLE DASHANGLE div ceiling DASHANGLE mul} {LABELANGLE HALFDASHANGLE sub DASHANGLE div round DASHANGLE mul HALFDASHANGLE add} ifelse } {HALFANGLE 60 add} ifelse def LABELCOLOR LABEL LABELSIZE LABELANGLE LABELRADIUS outsidecircletext %--------------------------------------------------------------------- orbit -- ORBITCOLOR 0.03 setlinewidth [1 r add 3.1415926535 180 div HALFDASHANGLE mul mul] 0 setdash newpath 0 0 1 r add 3 copy 30 LABELANGLE HALFANGLE add arcn stroke 60 LABELANGLE HALFANGLE sub 2 copy lt {arc stroke} {4 {pop} repeat} ifelse %------------------------------------------------------------------ copyright -- /COPYRIGHT (Graphic design by A. Nakonechny. Copyright (c) 1998, All rights reserved.) def LABELCOLOR LOGOFONT 32 div F 2 sqrt 0.99 mul dup neg moveto COPYRIGHT 90 rotate %show %---------------------------------------------------------------------- done -- showpage %%Trailer %%EOF luabind-1.1.1/doc/luabind.png000077500000000000000000000474471366245310300160470ustar00rootroot00000000000000PNG  IHDR?1gAMA|Q cHRMz%u0`:oNIDATxb?(#@;`4F4F4F4F4F4F4F4F4F4F4F4F4F4}իQ@[@,A .\afffqqv(;_~|@ehyyyYXX]Q@+@;`cc3222?~́v( qpp{/^hZ8|ҥ> sFM@fҒ~@;g0(ׯɗ/_rssKJJ?n߾H-Yh,MdPp…͛7 l311>1,tُ?k`Zə o` ̍N=ta>:y.h F39sfӦM,% ի{Kk ({30ٳy\#/R޸_{!<\\l * }v`Bāp7oY Ljjjҗ +&+((<9R48c,? …jH3Np⋃_j_ &Aᡬ,##..C#'шGٺu+ ,j*`B5. ?.'/l}@cUϚ5 XXZZ*))aSOrs:Ye<XEfc kiq㧢h7-'O\t CTUU2qCLLL`&9y򤦦&y *`UiA7Ct3_~=P%???#>C2xkmym@,jdӛ6howII1feN,0W\ٶmnW[N377tI4āe$01={ rz;%ϟ?N>RQQ,tebsC/5Ǐ߲6ܼAPrCrS ؛$ ظ_v-$5Gdee!lH9s(kll+<}V`@eHKK = 93õk^jJʺ_tǟJ%C4j`Jݲe3220:u[[['''`&_`x9`)~a` ` )I\= 4XPWvāarq`ON^ .i4YQݶ{R]bK!m`s Z & Lw]d 0A߹s;#r`RH%p=.`0f\S?}Ui!^QQQ4=ذFuN5{DE]@C,[[[Kb`\ߺuٳgw'C`cc[@eA`q lF@zݐЀ*<֖d-/^|}֣Go%&nd  XmA `G L L>,9ŋ@@DEE}PVFF^` Xk`+hÁZtЧ5]~S|۷_}]@ <&lMMM)XZXc*d"`ӧO33P޽W\AL-+`2: J`3,X0!Lrdf27-Fҳgπx o߾&,X| Z`gg L#??0;#0|nݺu}`kǎ;~f1hg_&$ٛ atg-V0Nf% f y`H*$WU9Z+qV)uC"aXHƘ)"@ {:LAЁRܟeι#@^~3(-0@';\%7q{xHi}{gv)j!~:z䉶6|Z!o4440 9`jDPPXJ`X@[deeܰ6+u]]]`f`|XbN?ϟs/ՅH@C5S6 >xXj(B X x`:L]! Ԁb` XKzF+++`&YE3灵0 &&&h+-/v@kk9PL& 0{Ry> i4cA R R6i1 V3Ҁ/p I_UU0>ylxԔ4G5H?Ł V`Y,v _4 10[m-{` >Dm큟?ƓΝ'k\#I@ X߼y~˗/8qɓ'` XS?d]\#PIv `s[5C?";{+9? R4M[`߸q>~hkk,ׯNB&m`FFFi` Çx.`~̙7n<|A^8lӧ;hR?ٳRRJB@ |I{pq`tÆ d LBBB`,!=|rpĀ {—Hk`0 7~5x̯_߰:po'0&%38Ap!w+%/=7Rho=&4Gp>qEV,k\U90EY^B=}kϰQI۹SqϞHiUK | ̱vXw޽c/@l333?`6Z'nڴ ]__r98pgggJ`@vQ |ҥ,ӧO?W @"5d / <~ ~0Sstt40e>}܁}YHxΝxN+33SNQ@<8`z4X20),ݻ@akɓ'!ãꐚ۷`}vqRǏ$4@pL+Vx  .]6~׽{R ϟgϞU.E7o_ӧ}غɓOB: @(H3|ի'Oe`.V66V`>qqQtrRRT46&)ʇ=he &KS6cnnk1:$jgϟ>u…<prg d$<xjF`o V>zE^essو]UU`u!LsBa/ z$ ` Rn׭[ٳ0L96A,B@@轣G gTg<}aa/_Џ&hOLch 3~1L*-.G /_8qfڵh |r1`MJJ֮؈ko8prJm G32&Aa,,d=̦Uw׮<%uPAPiǎ@7̚')I/kr,=0߽{wy {n`ouv*'O{Tum`-?~%C3#"Lz5~sq @ѻlxvvv{(l !`2!&&Hٺ/ؽ8c`}ݺֳ-HNvv=yytDM84,'ŋlIdo߾$'';@hG>\<32]<>~ѣ'O&~Be}UVN abb7/PZ̥4埡:lhHF?0K}`*먙5k.<>f7*`5뤕͛oV6 t[q`ggbcm8wܶm)l311AnF~ gRGF)/?q4Ft& aLCH];M ҥaxц 7o޼WQ¹nv Qڵ7NN W8 N#sl[w"9$Ĉ'l+-_`9}z`Z1 A7-/_7o @[~'NsOlm兄C;ľ#Ga_\ӦP h:t?@<==GB5kN< \E_` ::4VYg6g,^Kcǝ_׽T̙ 8 zz#G\ ]EE2 ԩS|7`%mmm)X_9 l0#)a޽]">~HA6f.)JK3!i/~@[ ;F...`=t" "`mC+xF&z׊ k;|+'~'M`,==(]WSÇ!ZYY[9=) 8D"69d1#Iۙ3Ο6˗_'6Rc@!\|N% hܾ}{˖-wRz ]^0Ndeadddae Ǐ'x?pnɓ}33I^/?<7L#1ު2@m jfŚlw͟?6Ӆ(<>>v6G!IX?*JOXlPT䀜 />z֭>X4 UTdICLq>>vFD ɓUVY[[;w.\LW u֬#{0Qae刊ҶV!dϟwX$/YrwO"ecc-.njrG82>={eee\Wĉ999݀o߾a̔x۸ߜv&&dsgVWu;_ , jN+׮]f `7ϙmzyH{>"lX`WP޼y 9´zOBU#VےFp@T.))g`OX߿ǂzǏԤdo{gʝgn([Xy$WD6KKYww˗>/^.\w o޼9p@sw,\x1'g8zFf!//fMKN#&ϩS uGCT yhקNڰav5 HV͚5k.^xʕgϞ133c=SJJJGGϟ?\_`=pMM0_~vu~#6+ΟlaA~ ,vL8=~EDi!իW7n>}¼B@$gw lxȢe`6\Uد:˗/vP{0x޽{!g@3Е/^|+(^ACp}Ocyϟ..F .`& l-[T4 HF.̎4 6e(B+,ccc8v|oݺl///`EAG#8ego_X??]7b>q.??7Niik׮S0QF9`` .^GHte`J;|W -"`},%,--;׿vUg z>---cG,1+dX￁8p mx`;2X!P2ey`~K.{rb0`n悜~Ldc{9#q۶x''j."|qS-/.q@5O,6f̘O{Ժ (CMM 聩GVU̬ȵH>O~[وmHN3}b33E.CۏoWbr8 LfFU ;./~[`=ET:fWGz bPd/_1]HNNАcѣG#UPWǏ/^@6{`ux񥸸#u&&SFÏ %x?nn3UUy3g6n(//EkVˡ]}O<vـ{&oٳϚS>}6Rwx 1\*l0MhхUD lVgR!x6e&@Ѫ ,}}}9Cl?tuD&ߠ12S?##Kl`H@(%%L!pڰb~}'ON$8p_Fy >[?/{w-HP=++U^^?~Y_|?L@7)p~P%AW/><=D %)HO 6\?tH,,K(ӱ4X?yn" `/S]݁\Vuu]O eWU"7?~o`.h'+/!b۳←`+HUU߼y2L6m ^i8ZCO XÇ%#3y{`+ϟР?=܈B,;v:E&#+Kű H+tzgSݻϣ 0 Y:T֓'\*.vn߾ H@3`ϣw˖-૸v<3o~;x?r)ϟ?c,,,"""89 (h~ŋ<<<ڡsSLtKuÿo?QF5mqTI9@~ r;Lr?`>thg J],.=ٺ6D. 3 Ӵvѭ[oGS?6;3ҥk^l _DQ9 R)O|va#߼O4<PL  w`+HDDDMM*NYʛ7oGpM5﫫Rrȃ7PM"3/?fbb֥muu{\Rȗ/_QN1}awx}_jys@KȩML~Qd"3yׯ~;8غիG3!~ŋx瀀Ta=xԙD" KSSZZZTq/;ƭO 0ϐAEEP>,)gLW`Ϟ**K/_$_JDf ##GUӧ?~LOH߿+*,]zr3~ĉ'T13gΜ;wK$ԐDQ#+L_p(N X/_~緄n>8 &cxJ 2! @ÇGkR/cbV8tW_!Jt⋿9`PRRf`ohPo3(x`pᩇǢ/Ȃ߄ iTo|K<<< @"e`׮{ U؟ؾ4ϟV$'{=6.0+ 4 ?M}XhP ;;ZA5Ę l-8pg؍Z&>xaQUr1;;]]Ξ}f͚tOYMGP3cYW?r^YBN BsW_Ysu }e` 5L!*` "3@ |6u'Mzк_}s;LLRR7o˝?}˗g!~2b?^"v@{/_{jti&030Y3Zu`;]a{,?@"9sΝ;߽{G 'j3 P#^$R,UƏf9VsrrR[ހm0bA߾FBD~Hrf :e: ȯt|h7`DϟԖ"Vׯ#0kn 3vBX#b"95FAG%"9v-`o 4#9?/V "`` #`{ p(=F̰x0i2&8=Nexӧ4 RV"9ppphhhRg+NI@΢'$'/( H￯_y̙<|%x˗EDD\ @{0J.ZP`v;_,ӀEDXRFO]]Yӯ_~_VcǍxu4(7U bffQgp4 ~(;hȥ@$!{H4 0S'j!)2,L&2$xK-VJ400XY TO `%Ŵll&_NdG“'{_.<<2 AQ 0oɓ}pz_@̟?RKl(+oa/}`9 JCC)S|LX99YqW` *s{ TWIy̼߬lRRjjB|@6V]}}ǯ_ASsPg,۷ NdLL,KY`t'/oN2#a" o..*jU lT0ϟ?޽ i@2)6 *ᡂu\eɒKsO?÷_=x0;伌?bϒsc*DC,p;L`@d rjk^vMVV699%qf\~8\޽`F$ΝWAAK׭62DV+%z[Ay*Errr$ d8"'qqq}ӧORaooRFp c{)DQjZ% 09ۯ_Sa4h$lʣ8w$ qȣEE_oF r2???0ӧSPFU?~'%M >dUlVn8ZP 0~u͚khkaܾԹh @x{vv 0:@9`ٳ=3t >lQg% k`%8B[[u@=;QVR*?ÀD>'0}*07qq EуPx 0Z3VV^]WKK*@IIO>vaa.u…hj75|h66 bbQQž-{"_)9;2/{`㜏OUUx4X2$i)v͒+t`ْ* @ .oATbL=ז:?A^Coﱯ_iw{+%Fׯ_~)I9 K Rq0 ?VVybbHqw߾/^||ųg_ i1GUU24T*fݼyrA3C ).ß{q֭7/^{_o|۷`c1Ҭg^ZlwViˊh%5vvfyyWf(6gr~̙goi 2g PI?999R'hp%$;om '):IJ UUam/_~ycν8Czr(_*1͛72SD |(7G ؉#7 Q🅅#~jkciLx`3Pg;!y'sλwEuDQxɾ}^|`jjJQled46`W__BFfWW%L+l)O-Qv,OIIc#h}!CTdte(򤬔͍eeg<_2[GWW:.NZ[C E@HHZjuY>LJ޼9~;P{1_`Ʀ1oV.ǏoݺE11N0Y_%% 4`4qÿuuũ?;;Wn9U$[ZZׯ_=HJXP!0`XXIoJJ2=n7R<`Z@XXV1W|vCYIEDa;fstT`e%b511fFd/B?TDiv,,,U<+L1 #..NNĀ76B`_7oEZH3%݄(y" "?]\4goU"!7X?@@T˳~ɓ"CwE]q ?wヒi{J>7B%1hrWgx6^dM71%jk-U"6p-T ןaa:5u#x?]]GBCW>vժ1]?VSN<7vvvEEEJA@__"5ՄI1\7PXD.]z…ҝf{&́H"|~/ENsz#"V{sǎ;ɄA݌I~هxؑE\GMMXp>~߾&;3 df"""۫W_mϝMUUXIIs.^|Ͽ!3\uvP3gϞ]v-accEiD oVVj&893tHFUPt`?23)V#Nomb$%-ZtyB~~Jo ޾} t߃㩘L-:=d+[膠팰׉D577+^^^2`~ pС5kAAAԝ ㏦ i ~Y6h}bDaPmmmEE;w*H:w?VZ#֖7o~  gaaa333 ѣGN_I!prRq z](!Lum`D0MMM` X 9s5<7Y+G,%DIrpp`rQ.(1g39zv hDTT>|H]//# ֖6~$U`ggM `zCG|($ i>5 .ёׯ$ͯ5676Qf{ՍR;wǏG|KKK1"v=ځ[n-_ϟ4ona439l„c+W^?|TRXX 6VNTn?|?}lQ:nb@f(8taIɎg|!N`#$DQA-1/̙A(@cǝÇ=/&"PGHHII]O>]jׯ===mll4@7\|YDD#1lzsʋK^#bøVz(ȍ$%ł5SSM!I};w𸺺r43N:a99(nfխ[o~\fEiXTUE444D5?,h 8~~s133 %$$kO`N=|?(C=#??DI"}7,mڴ̙3"&.>0U6=n~{W'O>XhsZ>AA33);;Ō !!M29@40oڲeˑ#GpHHȀL`GyK^#2#Ƚ] >>##q55\3sҐ4x38l޼@677@; 9aλO?xc_z'e0/++88(() h hPgϟ?UA``@<ykϟ|͵k޽ߟ?!ᙁF^f0qqq2IHpȨ hkKxyXBJ?hߕ @K.utt9o'O>ov٧?Aɓo~F^Ge84 !IIn]]@ R<|ƍNk@C#7>}}l`k^}o3c lG}=l L| RkA[ݻw2.hdQ0$Çw LT&J|ih4#Gڵ߿f>m!M~zsֿ|H F0CeaX޽x `wE,h~9oʡQ0P C>;vĉ&##cooK`& [>{< lzxx /33@ U`-7o;ĉ^j䀇ڵK^^mBe@C} YYC+:lc`9rԩ3g| 6,I [ Nxݑ#Gnݺ+R$&&???..B@92lF۷ؒۿ@ [Hg`񦮮4<' < =(33355:@W{{i}}}---UUՁv`BBB".7\>Hlj*`؟// Wϟ?؆43xٳg޽`,tuu-"`Nh#}t,\rر7o|& `7!!aX`\ׯ_ MCpnRX30<}X'pqq ߀^{=3HVPWWh < Y\\<00`0[>}sΓ'O߿$%%5M R0 mڴ XEӐ0 AnٲÁã*)) F! i NYhgvvv`&}`N>>>:g_~j:rrr&&&?ŋ={_fH 0?hyׯ@6%d'>yCn @vP?ۻKU>PfFFv7}8 ZUĸ#޹;hcynj7mh4 )U +gIݻt208pXo%0@ :|`^`IuH҇h"^^^`LFF&1 F3E2` L:0Cs (](((C*{le@-߿/_s"34r4F4d\ F3( F3( F3( ;2-IENDB`luabind-1.1.1/doc/make.bat000066400000000000000000000153741366245310300153170ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Luabind.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Luabind.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end luabind-1.1.1/doc/object.rst000066400000000000000000000251761366245310300157130ustar00rootroot00000000000000.. _part-object: Object ====== Since functions have to be able to take Lua values (of variable type) we need a wrapper around them. This wrapper is called ``luabind::object``. If the function you register takes an object, it will match any Lua value. To use it, you need to include ````. .. topic:: Synopsis .. parsed-literal:: class object { public: template 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 *implementation-defined* operator[](Key const&); template 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 *implementation-defined* operator[](T const& key) const void swap(object&); *implementation-defined* operator()(); template *implementation-defined* operator()(A0 const& a0); template *implementation-defined* operator()(A0 const& a0, A1 const& a1); /\* ... \*/ }; When you have a Lua object, you can assign it a new value with the assignment operator (=). When you do this, the ``default_policy`` will be used to make the conversion from C++ value to Lua. If your ``luabind::object`` is a table you can access its members through the operator[] or the Iterators_. The value returned from the operator[] is a proxy object that can be used both for reading 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 if you're trying to index something that cannot be indexed, you're on your own. Lua will call its ``panic()`` function. See :ref:`sec-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 to initialize 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 the top 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 push it onto the Lua stack by calling ``push()``. The operator== will call lua_compare() on the operands and return its result. The ``is_valid()`` function tells you whether the object has been initialized or not. When created with its default constructor, objects are invalid. To make an object valid, you can assign it a value. If you want to invalidate an object you can simply assign it an invalid object. The ``operator safe_bool_type()`` is equivalent to ``is_valid()``. This means that 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 can give it any number of parameters (currently the ``default_policy`` will be used for the conversion). The returned object refers to the return value (currently only one return value is supported). This operator may throw ``luabind::error`` if the function call fails. If you want to specify policies to your function call, you can use index-operator (operator[]) on the function call, and give the 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 the pointer passed in to the lua-function. It's important that all instances of object have been destructed by the time the Lua state is closed. The object will keep a pointer to the lua state and release 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(table[5]) << "\n"; } } If you take a ``luabind::object`` as a parameter to a function, any Lua value will match that parameter. That's why we have to make sure it's a table before we 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 string conversion 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 metamethod of the object (if there is any) when the value is retrieved. This iterator is simply called ``luabind::iterator``. The other iterator is called ``luabind::raw_iterator`` and will bypass the metamethod and give the true contents of the table. They have identical interfaces, which implements the ForwardIterator_ concept. Apart from the 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 be used with object. Passing an object as the parameter to the iterator will construct the iterator to refer to the first element in the object. The default constructor will initialize the iterator to the one-past-end iterator. This is used to test for the end of the sequence. The value type of the iterator is an implementation defined proxy type which supports the same operations as ``luabind::object``. Which means that in most cases you can just treat it as an ordinary object. The difference is that any assignments to this proxy will result in the value being inserted at the iterators position, in the table. The ``key()`` member returns the key used by the iterator when indexing the associated 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 constructor and hence refer to the end of the sequence. This example will simply iterate over 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 void settable(object const& o, K const& key, T const& value); template object gettable(object const& o, K const& key); template void rawset(object const& o, K const& key, T const& value); template 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. Which means 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 the true value of the table entry. :: template T object_cast(object const&); template T object_cast(object const&, Policies); template boost::optional object_cast_nothrow(object const&); template boost::optional object_cast_nothrow(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 cast cannot be made a ``cast_failed`` exception will be thrown. If you have defined LUABIND_NO_ERROR_CHECKING (see :ref:`part-build-options`) no checking will occur, and if the cast is invalid the application may very well crash. The nothrow versions will return an uninitialized ``boost::optional`` object, to indicate that the cast could not be performed. The function signatures of all of the above functions are really templates for the object parameter, but the intention is that you should only pass objects 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. :: object getmetatable(object const& obj); void setmetatable(object const& obj, object const& metatable); These functions get and set the metatable of a Lua object. :: lua_CFunction tocfunction(object const& value); template T* touserdata(object const& value) These extract values from the object at a lower level than ``object_cast()``. :: object getupvalue(object const& function, int index); void setupvalue(object const& function, int index, object const& value); These get and set the upvalues of ``function``. Assigning nil ------------- To set a table entry to ``nil``, you can use ``luabind::nil``. It will avoid having to take the detour by first assigning ``nil`` to an object and then assign 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; luabind-1.1.1/doc/policies.rst000066400000000000000000000225271366245310300162510ustar00rootroot00000000000000.. _part-policies: Policies ======== Sometimes it is necessary to control how luabind passes arguments and return value, to do this we have policies. All policies use an index to associate them with an argument in the function signature. These indices are ``result`` and ``_N`` (where ``N >= 1``). When dealing with member functions ``_1`` refers to the ``this`` pointer. .. contents:: Policies currently implemented :local: :depth: 1 .. include:: policies/adopt.rst .. include:: policies/dependency.rst .. include:: policies/out_value.rst .. include:: policies/pure_out_value.rst .. include:: policies/return_reference_to.rst .. include:: policies/copy.rst .. include:: policies/discard_result.rst .. include:: policies/return_stl_iterator.rst .. include:: policies/raw.rst .. include:: policies/yield.rst .. old policies section =================================================== Copy ---- This will make a copy of the parameter. This is the default behavior when passing parameters by-value. Note that this can only be used when passing from C++ to Lua. This policy requires that the parameter type has a copy constructor. To use this policy you need to include ``luabind/copy_policy.hpp``. Adopt ----- This will transfer ownership of the parameter. Consider making a factory function in C++ and exposing it to lua:: base* create_base() { return new base(); } ... module(L) [ def("create_base", create_base) ]; Here we need to make sure Lua understands that it should adopt the pointer returned by the factory-function. This can be done using the adopt-policy. :: module(L) [ def(L, "create_base", adopt(return_value)) ]; To specify multiple policies we just separate them with '+'. :: base* set_and_get_new(base* ptr) { base_ptrs.push_back(ptr); return new base(); } module(L) [ def("set_and_get_new", &set_and_get_new, adopt(return_value) + adopt(_1)) ]; When Lua adopts a pointer, it will call delete on it. This means that it cannot adopt pointers allocated with another allocator than new (no malloc for example). To use this policy you need to include ``luabind/adopt_policy.hpp``. Dependency ---------- The dependency policy is used to create life-time dependencies between values. Consider the following example:: struct A { B member; const B& get_member() { return member; } }; When wrapping this class, we would do something like:: module(L) [ class_("A") .def(constructor<>()) .def("get_member", &A::get_member) ]; However, since the return value of get_member is a reference to a member of A, this will create some life-time issues. For example:: Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio a = A() b = a:get_member() -- b points to a member of a a = nil collectgarbage(0) -- since there are no references left to a, it is -- removed -- at this point, b is pointing into a removed object When using the dependency-policy, it is possible to tell luabind to tie the lifetime of one object to another, like this:: module(L) [ class_("A") .def(constructor<>()) .def("get_member", &A::get_member, dependency(result, _1)) ]; This will create a dependency between the return-value of the function, and the self-object. This means that the self-object will be kept alive as long as the result is still alive. :: Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio a = A() b = a:get_member() -- b points to a member of a a = nil collectgarbage(0) -- a is dependent on b, so it isn't removed b = nil collectgarbage(0) -- all dependencies to a gone, a is removed To use this policy you need to include ``luabind/dependency_policy.hpp``. Return reference to ------------------- It is very common to return references to arguments or the this-pointer to allow for chaining in C++. :: struct A { float val; A& set(float v) { val = v; return *this; } }; When luabind generates code for this, it will create a new object for the return-value, pointing to the self-object. This isn't a problem, but could be a bit inefficient. When using the return_reference_to-policy we have the ability to tell luabind that the return-value is already on the Lua stack. :: module(L) [ class_("A") .def(constructor<>()) .def("set", &A::set, return_reference_to(_1)) ]; Instead of creating a new object, luabind will just copy the object that is already on the stack. .. warning:: This policy ignores all type information and should be used only it situations where the parameter type is a perfect match to the return-type (such as in the example). To use this policy you need to include ``luabind/return_reference_to_policy.hpp``. Out value --------- This policy makes it possible to wrap functions that take non const references as its parameters with the intention to write return values to them. :: void f(float& val) { val = val + 10.f; } or :: void f(float* val) { *val = *val + 10.f; } Can be wrapped by doing:: module(L) [ def("f", &f, out_value(_1)) ]; When invoking this function from Lua it will return the value assigned to its parameter. :: Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio > a = f(10) > print(a) 20 When this policy is used in conjunction with user define types we often need to do ownership transfers. :: struct A; void f1(A*& obj) { obj = new A(); } void f2(A** obj) { *obj = new A(); } Here we need to make sure luabind takes control over object returned, for this we use the adopt policy:: module(L) [ class_("A"), def("f1", &f1, out_value(_1, adopt(_2))) def("f2", &f2, out_value(_1, adopt(_2))) ]; Here we are using adopt as an internal policy to out_value. The index specified, _2, means adopt will be used to convert the value back to Lua. Using _1 means the policy will be used when converting from Lua to C++. To use this policy you need to include ``luabind/out_value_policy.hpp``. Pure out value -------------- This policy works in exactly the same way as out_value, except that it replaces the parameters with default-constructed objects. :: void get(float& x, float& y) { x = 3.f; y = 4.f; } ... module(L) [ def("get", &get, pure_out_value(_1) + pure_out_value(_2)) ]; :: Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio > x, y = get() > print(x, y) 3 5 Like out_value, it is possible to specify an internal policy used then converting the values back to Lua. :: void get(test_class*& obj) { obj = new test_class(); } ... module(L) [ def("get", &get, pure_out_value(_1, adopt(_1))) ]; Discard result -------------- This is a very simple policy which makes it possible to throw away the value returned by a C++ function, instead of converting it to Lua. This example makes sure the this reference never gets converted to Lua. :: struct simple { simple& set_name(const std::string& n) { name = n; return *this; } std::string name; }; ... module(L) [ class_("simple") .def("set_name", &simple::set_name, discard_result) ]; To use this policy you need to include ``luabind/discard_result_policy.hpp``. Return STL iterator ------------------- This policy converts an STL container to a generator function that can be used in Lua to iterate over the container. It works on any container that defines ``begin()`` and ``end()`` member functions (they have to return iterators). It can be used like this:: struct A { std::vector names; }; module(L) [ class_("A") .def_readwrite("names", &A::names, return_stl_iterator) ]; The Lua code to iterate over the container:: a = A() for name in a.names do print(name) end To use this policy you need to include ``luabind/iterator_policy.hpp``. Yield ----- This policy will cause the function to always yield the current thread when returning. See the Lua manual for restrictions on yield. luabind-1.1.1/doc/policies/000077500000000000000000000000001366245310300155075ustar00rootroot00000000000000luabind-1.1.1/doc/policies/adopt.rst000066400000000000000000000013321366245310300173470ustar00rootroot00000000000000adopt ----- Motivation ~~~~~~~~~~ Used to transfer ownership across language boundaries. Defined in ~~~~~~~~~~ :: #include Synopsis ~~~~~~~~ :: adopt(index) Parameters ~~~~~~~~~~ ============= =============================================================== Parameter Purpose ============= =============================================================== ``index`` The index which should transfer ownership, ``_N`` or ``result`` ============= =============================================================== Example ~~~~~~~ :: X* create() { return new X; } .. parsed-literal:: module(L) [ def("create", &create, **adopt(result)**) ]; luabind-1.1.1/doc/policies/copy.rst000066400000000000000000000017521366245310300172200ustar00rootroot00000000000000copy ---- Motivation ~~~~~~~~~~ This will make a copy of the parameter. This is the default behavior when passing parameters by-value. Note that this can only be used when passing from C++ to Lua. This policy requires that the parameter type has an accessible copy constructor. Defined in ~~~~~~~~~~ :: #include Synopsis ~~~~~~~~ :: copy(index) Parameters ~~~~~~~~~~ ============= =============================================================== Parameter Purpose ============= =============================================================== ``index`` The index to copy. ``result`` when used while wrapping C++ functions. ``_N`` when passing arguments to Lua. ============= =============================================================== Example ~~~~~~~ :: X* get() { static X instance; return &instance; } .. parsed-literal:: module(L) [ def("create", &create, **copy(result)**) ]; luabind-1.1.1/doc/policies/dependency.rst000066400000000000000000000017201366245310300203570ustar00rootroot00000000000000dependency ---------- Motivation ~~~~~~~~~~ The dependency policy is used to create life-time dependencies between values. This is needed for example when returning internal references to some class. Defined in ~~~~~~~~~~ :: #include Synopsis ~~~~~~~~ :: dependency(nurse_index, patient_index) Parameters ~~~~~~~~~~ ================= ========================================================== Parameter Purpose ================= ========================================================== ``nurse_index`` The index which will keep the patient alive. ``patient_index`` The index which will be kept alive. ================= ========================================================== Example ~~~~~~~ :: struct X { B member; B& get() { return member; } }; .. parsed-literal:: module(L) [ class_("X") .def("get", &X::get, **dependency(result, _1)**) ]; luabind-1.1.1/doc/policies/discard_result.rst000066400000000000000000000010751366245310300212530ustar00rootroot00000000000000discard_result -------------- Motivation ~~~~~~~~~~ This is a very simple policy which makes it possible to throw away the value returned by a C++ function, instead of converting it to Lua. Defined in ~~~~~~~~~~ :: #include Synopsis ~~~~~~~~ :: discard_result Example ~~~~~~~ :: struct X { X& set(T n) { ... return *this; } }; .. parsed-literal:: module(L) [ class_("X") .def("set", &simple::set, **discard_result**) ]; luabind-1.1.1/doc/policies/out_value.rst000066400000000000000000000030031366245310300202400ustar00rootroot00000000000000.. _policy-out_value: out_value --------- Motivation ~~~~~~~~~~ This policy makes it possible to wrap functions that take non-const references or pointer to non-const as it's parameters with the intention to write return values to them. Since it's impossible to pass references to primitive types in lua, this policy will add another return value with the value after the call. If the function already has one return value, one instance of this policy will add another return value (read about multiple return values in the lua manual). Defined in ~~~~~~~~~~ :: #include Synopsis ~~~~~~~~ :: out_value(index, policies = none) Parameters ~~~~~~~~~~ =============== ============================================================= Parameter Purpose =============== ============================================================= ``index`` The index of the parameter to be used as an out parameter. ``policies`` The policies used internally to convert the out parameter to/from Lua. ``_1`` means **to** C++, ``_2`` means **from** C++. =============== ============================================================= Example ~~~~~~~ :: void f1(float& val) { val = val + 10.f; } void f2(float* val) { *val = *val + 10.f; } .. parsed-literal:: module(L) [ def("f", &f, **out_value(_1)**) ]; .. code-block:: lua Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio > print(f1(10)) 20 > print(f2(10)) 20 luabind-1.1.1/doc/policies/pure_out_value.rst000066400000000000000000000024431366245310300213020ustar00rootroot00000000000000.. _policy-pure_out_value: pure_out_value -------------- Motivation ~~~~~~~~~~ This works exactly like ``out_value``, except that it will pass a default constructed object instead of converting an argument from Lua. This means that the parameter will be removed from the lua signature. Defined in ~~~~~~~~~~ :: #include Synopsis ~~~~~~~~ :: pure_out_value(index, policies = none) Parameters ~~~~~~~~~~ =============== ============================================================= Parameter Purpose =============== ============================================================= ``index`` The index of the parameter to be used as an out parameter. ``policies`` The policies used internally to convert the out parameter to Lua. ``_1`` is used as the internal index. =============== ============================================================= Example ~~~~~~~ Note that no values are passed to the calls to ``f1`` and ``f2``. :: void f1(float& val) { val = 10.f; } void f2(float\* val) { \*val = 10.f; } .. parsed-literal:: module(L) [ def("f", &f, **pure_out_value(_1)**) ]; .. code-block:: lua Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio > print(f1()) 10 > print(f2()) 10 luabind-1.1.1/doc/policies/raw.rst000066400000000000000000000021061366245310300170310ustar00rootroot00000000000000raw --- .. note:: ``raw()`` has been deprecated. ``lua_State*`` parameters are automatically handled by luabind. Motivation ~~~~~~~~~~ This converter policy will pass through the ``lua_State*`` unmodified. This can be useful for example when binding functions that need to return a ``luabind::object``. The parameter will be removed from the function signature, decreasing the function arity by one. Defined in ~~~~~~~~~~ :: #include Synopsis ~~~~~~~~ :: raw(index) Parameters ~~~~~~~~~~ ============= =============================================================== Parameter Purpose ============= =============================================================== ``index`` The index of the lua_State* parameter. ============= =============================================================== Example ~~~~~~~ :: void greet(lua_State* L) { lua_pushstring(L, "hello"); } .. parsed-literal:: module(L) [ def("greet", &greet, **raw(_1)**) ]; .. code-block:: lua > print(greet()) hello luabind-1.1.1/doc/policies/return_reference_to.rst000066400000000000000000000031251366245310300223010ustar00rootroot00000000000000return_reference_to ------------------- Motivation ~~~~~~~~~~ It is very common to return references to arguments or the this-pointer to allow for chaining in C++. :: struct A { float val; A& set(float v) { val = v; return *this; } }; When luabind generates code for this, it will create a new object for the return-value, pointing to the self-object. This isn't a problem, but could be a bit inefficient. When using the return_reference_to-policy we have the ability to tell luabind that the return-value is already on the lua stack. Defined in ~~~~~~~~~~ :: #include Synopsis ~~~~~~~~ :: return_reference_to(index) Parameters ~~~~~~~~~~ ========= ============================================================= Parameter Purpose ========= ============================================================= ``index`` The argument index to return a reference to, any argument but not ``result``. ========= ============================================================= Example ~~~~~~~ :: struct A { float val; A& set(float v) { val = v; return *this; } }; .. parsed-literal:: module(L) [ class_("A") .def(constructor<>()) .def("set", &A::set, **return_reference_to(_1)**) ]; .. warning:: This policy ignores all type information and should be used only it situations where the parameter type is a perfect match to the return-type (such as in the example). luabind-1.1.1/doc/policies/return_stl_iterator.rst000066400000000000000000000013461366245310300223570ustar00rootroot00000000000000return_stl_iterator ------------------- Motivation ~~~~~~~~~~ This policy converts an STL container to a generator function that can be used in lua to iterate over the container. It works on any container that defines ``begin()`` and ``end()`` member functions (they have to return iterators). Defined in ~~~~~~~~~~ :: #include Synopsis ~~~~~~~~ :: return_stl_iterator Example ~~~~~~~ :: struct X { std::vector names; }; .. parsed-literal:: module(L) [ class_("A") .def_readwrite("names", &X::names, **return_stl_iterator**) ]; .. code-block:: lua > a = A() > for name in a.names do > print(name) > end luabind-1.1.1/doc/policies/yield.rst000066400000000000000000000007121366245310300173470ustar00rootroot00000000000000.. _policy-yield: yield ---------------- Motivation ~~~~~~~~~~ Makes a C++ function yield when returning. Defined in ~~~~~~~~~~ .. parsed-literal:: #include Synopsis ~~~~~~~~ .. parsed-literal:: yield Example ~~~~~~~ :: void do_thing_that_takes_time() { // ... } .. parsed-literal:: module(L) [ def("do_thing_that_takes_time", &do_thing_that_takes_time, **yield**) ]; luabind-1.1.1/doc/scopes.rst000066400000000000000000000035631366245310300157350ustar00rootroot00000000000000Scopes ====== Everything that gets registered in Lua is registered in a given Lua table, in a namespace (Lua table at given name), or in the global scope (called module). All registrations must be surrounded by its scope. To define a module, the ``luabind::module`` class is used. It is used like this:: module(L) [ // declarations ]; This will register all declared functions or classes in the global namespace in Lua. You can also register into a custom Lua table wrapped in a :ref:`part-object`:: object mod = newtable(L); module(L, mod) [ // declarations ]; You can then directly use all object manipulation functions on ``mod``. If you just want to have a namespace for your module (like the standard libraries) 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. It works 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") .def(constructor), def("h", &h) ]; More about the actual declarations in the :ref:`part-functions` and :ref:`part-classes` sections. luabind-1.1.1/doc/split-registration.rst000066400000000000000000000014271366245310300203010ustar00rootroot00000000000000.. _part-split-registration: Splitting up the registration ============================= It is possible to split up a module registration into several translation units without making each registration dependent on the module it's being registered in. ``a.cpp``:: luabind::scope register_a() { return class_("a") .def("f", &a::f) ; } ``b.cpp``:: luabind::scope register_b() { return class_("b") .def("g", &b::g) ; } ``module_ab.cpp``:: luabind::scope register_a(); luabind::scope register_b(); void register_module(lua_State* L) { module("b", L) [ register_a(), register_b() ]; } luabind-1.1.1/doc/style.css000066400000000000000000000116261366245310300155600ustar00rootroot00000000000000/* :Author: David Goodger :Contact: goodger@users.sourceforge.net :date: $Date$ :version: $Revision$ :copyright: This stylesheet has been placed in the public domain. Default cascading style sheet for the HTML output of Docutils. */ p { text-align: justify; } .first { margin-top: 0 } .last { margin-bottom: 0 } a.toc-backref { text-decoration: none ; color: black } dt { /* used in FAQ */ font-weight: bold ; margin-bottom: 0.2em } dl { margin-left: 0.5em ; margin-right: 10em } h3 { font-size: 90% } dd { margin-bottom: 0.5em } div.abstract { margin: 2em 5em } div.abstract p.topic-title { font-weight: bold ; text-align: center } div.attention, div.caution, div.danger, div.error, div.hint, div.important, div.note, div.tip, div.warning, div.admonition { margin: 2em ; border: medium outset ; padding: 1em } div.attention p.admonition-title, div.caution p.admonition-title, div.danger p.admonition-title, div.error p.admonition-title, div.warning p.admonition-title { color: red ; font-weight: bold ; font-family: sans-serif } div.hint p.admonition-title, div.important p.admonition-title, div.note p.admonition-title, div.tip p.admonition-title, div.admonition p.admonition-title { font-weight: bold ; font-family: sans-serif } div.dedication { margin: 2em 5em ; text-align: center ; font-style: italic } div.dedication p.topic-title { font-weight: bold ; font-style: normal } div.figure { margin-left: 2em } div.footer, div.header { font-size: smaller } div.sidebar { margin-left: 1em ; border: medium outset ; padding: 0em 1em ; background-color: #ffffee ; width: 40% ; float: right ; clear: right } div.sidebar p.rubric { font-family: sans-serif ; font-size: medium } div.system-messages { margin: 5em } div.system-messages h1 { color: red } div.system-message { border: medium outset ; padding: 1em } div.system-message p.system-message-title { color: red ; font-weight: bold } div.topic { margin: 2em } h1.title { text-align: center } h2.subtitle { text-align: center } hr { width: 75% } ol.simple, ul.simple { margin-bottom: 1em } ol.arabic { list-style: decimal } ol.loweralpha { list-style: lower-alpha } ol.upperalpha { list-style: upper-alpha } ol.lowerroman { list-style: lower-roman } ol.upperroman { list-style: upper-roman } p.attribution { text-align: right ; margin-left: 50% } p.caption { font-style: italic } p.credits { font-style: italic ; font-size: smaller } p.label { white-space: nowrap } p.rubric { font-weight: bold ; font-size: larger ; color: maroon ; text-align: center } p.sidebar-title { font-family: sans-serif ; font-weight: bold ; font-size: larger } p.sidebar-subtitle { font-family: sans-serif ; font-weight: bold } p.topic-title { font-weight: bold } pre.address { margin-bottom: 0 ; margin-top: 0 ; font-family: serif ; font-size: 100% } pre.line-block { font-family: serif ; font-size: 100% } pre.literal-block, pre.doctest-block { margin-left: 2em ; margin-right: 2em ; /* padding-left: 1em ;*/ background-color: #eeeeee ; /* border-left: solid 3px #c0c0c0*/ } span.classifier { font-family: sans-serif ; font-style: oblique } span.classifier-delimiter { font-family: sans-serif ; font-weight: bold } span.interpreted { font-family: sans-serif } span.option { white-space: nowrap } span.option-argument { font-style: italic } span.pre { white-space: pre } span.problematic { color: red } table { margin-top: 0.5em ; margin-bottom: 0.5em } table.citation { border-left: solid thin gray ; padding-left: 0.5ex } table.docinfo { margin: 2em 4em ; border: none } table.footnote { border-left: solid thin black ; padding-left: 0.5ex } td, th { padding-left: 0.5em ; padding-right: 0.5em ; vertical-align: top } th.docinfo-name, th.field-name { font-weight: bold ; text-align: left ; white-space: nowrap ; border: none ; background-color: #f0f0f0 } h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt { font-size: 100% ; font-family: serif } /*h1 { font-family: Arial, Helvetica, sans-serif; font-weight: bold; text-align: left; font-size: 140%; } h2 { font-family: Arial, Helvetica, sans-serif; font-weight: bold; text-align: left; font-size: 110%; } h3 { font-family: "courier new", courier, monospace; font-weight: bold; text-align: left; font-size: 100%; } */ tt { /*background-color: #eeeeee*/ color: #102eb0 } ul.auto-toc { list-style-type: none } /* --- */ table { border-collapse: collapse; border: none; /* border-bottom: 1px solid black;*/ margin-left: 1em; } td, th { border: none; } th { /* border-top: 1px solid black;*/ border-bottom: 1px solid black; text-align: left; } a:link { font-weight: bold; color: #003366; text-decoration: none; } a:visited { font-weight: bold; color: #003366; text-decoration: none; } h3 { text-transform: uppercase } luabind-1.1.1/doc/userdefined-converters.rst000066400000000000000000000026661366245310300211310ustar00rootroot00000000000000Adding converters for user defined types ======================================== It is possible to get luabind to handle user defined types like it does the built in types by specializing ``luabind::default_converter<>``: :: struct int_wrapper { int_wrapper(int value) : value(value) {} int value; }; namespace luabind { template <> struct default_converter : native_converter_base { static int compute_score(lua_State* L, int index) { return lua_type(L, index) == LUA_TNUMBER ? 0 : -1; } X from(lua_State* L, int index) { return X(lua_tonumber(L, index)); } void to(lua_State* L, X const& x) { lua_pushnumber(L, x.value); } }; template <> struct default_converter : default_converter {}; } Note that ``default_converter<>`` is instantiated for the actual argument and return types of the bound functions. In the above example, we add a specialization for ``X const&`` that simply forwards to the ``X`` converter. This lets us export functions which accept ``X`` by const reference. ``native_converter_base<>`` should be used as the base class for the specialized converters. It simplifies the converter interface, and provides a mean for backward compatibility since the underlying interface is in flux.luabind-1.1.1/examples/000077500000000000000000000000001366245310300147515ustar00rootroot00000000000000luabind-1.1.1/examples/any_converter/000077500000000000000000000000001366245310300176275ustar00rootroot00000000000000luabind-1.1.1/examples/any_converter/Jamfile000077500000000000000000000001331366245310300211210ustar00rootroot00000000000000import modules ; exe any_converter : any_converter.cpp /luabind//luabind ; luabind-1.1.1/examples/any_converter/any_converter.cpp000066400000000000000000000037111366245310300232130ustar00rootroot00000000000000#include extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } bool dostring(lua_State* L, const char* str) { if (luaL_loadbuffer(L, str, std::strlen(str), str) || lua_pcall(L, 0, 0, 0)) { const char* a = lua_tostring(L, -1); std::cout << a << "\n"; lua_pop(L, 1); return true; } return false; } #include #include #include template struct convert_any { static void convert(lua_State* L, const boost::any& a) { luabind::detail::convert_to_lua(L, *boost::any_cast(&a)); } }; std::map any_converters; template void register_any_converter() { any_converters[&typeid(T)] = convert_any::convert; } namespace luabind { namespace converters { yes_t is_user_defined(by_value); yes_t is_user_defined(by_const_reference); void convert_cpp_to_lua(lua_State* L, const boost::any& a) { typedef void(*conv_t)(lua_State* L, const boost::any&); conv_t conv = any_converters[&a.type()]; conv(L, a); } } } boost::any f(bool b) { if (b) return "foobar"; else return 3.5f; } int main() { register_any_converter(); register_any_converter(); register_any_converter(); register_any_converter(); lua_State* L = luaL_newstate(); #if LUA_VERSION_NUM >= 501 luaL_openlibs(L); #else lua_baselibopen(L); #endif using namespace luabind; open(L); module(L) [ def("f", &f) ]; dostring(L, "print( f(true) )"); dostring(L, "print( f(false) )"); dostring(L, "function update(p) print(p) end"); boost::any param = std::string("foo"); luabind::call_function(L, "update", param); lua_close(L); } luabind-1.1.1/examples/cln/000077500000000000000000000000001366245310300155255ustar00rootroot00000000000000luabind-1.1.1/examples/cln/README000066400000000000000000000001441366245310300164040ustar00rootroot00000000000000To build this example you need to have CLN installed. It can be found at http://www.ginac.de/CLN/ luabind-1.1.1/examples/cln/cln_test.cpp000066400000000000000000000073371366245310300200560ustar00rootroot00000000000000#include extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } #include void bind_cln(lua_State* L) { using namespace luabind; using namespace cln; module(L) [ // real numbers class_("cl_R") .def(constructor<>()) .def(constructor()) .def(constructor()) .def(constructor()) .def(tostring(const_self)) .def(-self) .def(const_self + const_self) .def(const_self - const_self) .def(const_self * const_self) .def(const_self / const_self) .def(const_self <= const_self) .def(const_self < const_self) .def(const_self == const_self) .def(other() + const_self) .def(other() - const_self) .def(other() * const_self) .def(other() / const_self) .def(other() <= const_self) .def(other() < const_self) .def(const_self + other()) .def(const_self - other()) .def(const_self * other()) .def(const_self / other()) .def(const_self <= other()) .def(const_self < other()) , // rational numbers class_("cl_RA") .def(constructor<>()) .def(constructor()) .def(constructor()) .def(constructor()) .def(tostring(const_self)) .def(-self) .def(const_self + const_self) .def(const_self - const_self) .def(const_self * const_self) .def(const_self / const_self) .def(const_self <= const_self) .def(const_self < const_self) .def(const_self == const_self) .def(other() + const_self) .def(other() - const_self) .def(other() * const_self) .def(other() / const_self) .def(other() <= const_self) .def(other() < const_self) .def(const_self + other()) .def(const_self - other()) .def(const_self * other()) .def(const_self / other()) .def(const_self <= other()) .def(const_self < other()) , // integers class_("cl_I") .def(constructor<>()) .def(constructor()) .def(constructor()) .def(constructor()) .def(tostring(const_self)) .def(-self) .def(const_self + const_self) .def(const_self - const_self) .def(const_self * const_self) .def(const_self <= const_self) .def(const_self < const_self) .def(const_self == const_self) .def(other() + const_self) .def(other() - const_self) .def(other() * const_self) .def(other() <= const_self) .def(other() < const_self) .def(const_self + other()) .def(const_self - other()) .def(const_self * other()) .def(const_self <= other()) .def(const_self < other()) , def("factorial", &cln::factorial), def("sqrt", (const cl_R(*)(const cl_R&))&cln::sqrt) ]; } int main() { lua_State* L = luaL_newstate(); lua_baselibopen(L); lua_mathlibopen(L); luabind::open(L); bind_cln(L); lua_dofile(L, "cln_test.lua"); lua_close(L); return 0; } luabind-1.1.1/examples/cln/cln_test.lua000066400000000000000000000010061366245310300200400ustar00rootroot00000000000000 a = factorial(41) b = factorial(42) print('a = fac(41) = ' .. tostring(a)) print('b = fac(42) = ' .. tostring(b)) print('b / a = ' .. tostring(b / a)) c = a * 42 d = sqrt(cl_R(10)) print('d = sqrt(10) = ' .. tostring(d)) if c == b then print('equality operator test: ok') else print('equality operator test: failed') end -- prints -- a = fac(41) = 33452526613163807108170062053440751665152000000000 -- b = fac(42) = 1405006117752879898543142606244511569936384000000000 -- b / a = 42 -- d = sqrt(10) = 3.1622777 luabind-1.1.1/examples/filesystem/000077500000000000000000000000001366245310300171355ustar00rootroot00000000000000luabind-1.1.1/examples/filesystem/Jamfile000077500000000000000000000003401366245310300204270ustar00rootroot00000000000000import modules ; BOOST_ROOT = [ modules.peek : BOOST_ROOT ] ; use-project /boost : $(BOOST_ROOT) ; exe filesystem : filesystem.cpp /boost/filesystem//boost_filesystem/static /luabind//luabind ; luabind-1.1.1/examples/filesystem/directory_iterator.hpp000077500000000000000000000071711366245310300235740ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_DIRECTORY_ITERATOR_HPP_INCLUDED #define LUABIND_DIRECTORY_ITERATOR_HPP_INCLUDED #include #include #include #include namespace luabind { namespace detail { template struct dir_iterator_state { typedef dir_iterator_state self_t; static int step(lua_State* L) { self_t& state = *static_cast(lua_touserdata(L, lua_upvalueindex(1))); if (state.start == state.end) { lua_pushnil(L); return 1; } else { convert_to_lua(L, *state.start); } ++state.start; return 1; } dir_iterator_state(const Iter& s, const Iter& e) : start(s) , end(e) {} Iter start; Iter end; }; struct dir_iterator_converter { template void apply(lua_State* L, const T& c) { typedef boost::filesystem::directory_iterator iter_t; typedef dir_iterator_state state_t; // note that this should be destructed, for now.. just hope that iterator // is a pod void* iter = lua_newuserdata(L, sizeof(state_t)); new (iter) state_t(iter_t(c), iter_t()); lua_pushcclosure(L, state_t::step, 1); } template void apply(lua_State* L, T& c) { typedef boost::filesystem::directory_iterator iter_t; typedef dir_iterator_state state_t; // note that this should be destructed, for now.. just hope that iterator // is a pod void* iter = lua_newuserdata(L, sizeof(state_t)); new (iter) state_t(iter_t(c), iter_t()); lua_pushcclosure(L, state_t::step, 1); } }; struct dir_iterator_policy : conversion_policy<0> { static void precall(lua_State*, const index_map&) {} static void postcall(lua_State*, const index_map&) {} template struct generate_converter { typedef dir_iterator_converter type; }; }; }} namespace luabind { namespace { LUABIND_ANONYMOUS_FIX detail::policy_cons return_directory_iterator; } } #endif // LUABIND_ITERATOR_POLICY_HPP_INCLUDED luabind-1.1.1/examples/filesystem/filesystem.cpp000077500000000000000000000062501366245310300220330ustar00rootroot00000000000000#include extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } #include #include #include #include #include "directory_iterator.hpp" const boost::filesystem::path& identity(const boost::filesystem::path& x) { return x; } void bind_filesystem(lua_State* L) { using namespace luabind; using namespace boost::filesystem; namespace fs = boost::filesystem; module(L, "filesystem") [ class_("path") .def(constructor<>()) .def(constructor()) .def("string", &fs::path::string) .def("native_file_string", &fs::path::native_file_string) .def("native_directory_string", &fs::path::native_directory_string) .def("root_path", &fs::path::root_path) .def("root_name", &fs::path::root_name) .def("root_directory", &fs::path::root_directory) .def("relative_path", &fs::path::relative_path) .def("leaf", &fs::path::leaf) .def("branch_path", &fs::path::branch_path) .def("empty", &fs::path::empty) .def("is_complete", &fs::path::is_complete) .def("is_directory", &fs::is_directory) .def("is_empty", &fs::is_empty) .def("has_root_path", &fs::path::has_root_path) .def("has_root_name", &fs::path::has_root_name) .def("has_root_directory", &fs::path::has_root_directory) .def("has_relative_path", &fs::path::has_relative_path) .def("has_leaf", &fs::path::has_leaf) .def("has_branch_path", &fs::path::has_branch_path) .def(const_self / const_self) .def(other() / const_self) .def(const_self / other()) // .property("contents", &identity, return_directory_iterator) , def("exists", &fs::exists), def("is_directory", &fs::is_directory), def("is_empty", &fs::is_empty), def("create_directory", &fs::create_directory), def("remove", &fs::remove), def("remove_all", &fs::remove_all), def("rename", &fs::rename), def("copy_file", &fs::copy_file), def("initial_path", &fs::initial_path), def("current_path", &fs::current_path), def("complete", &fs::complete), def("system_complete", &fs::system_complete) ]; } int main(int argc, const char* argv[]) { lua_State* L = luaL_newstate(); luaopen_base(L); luaopen_string(L); luaopen_table(L); luaopen_math(L); luaopen_io(L); luaopen_debug(L); if (argc < 2) { std::cout << "This example will bind parts of the boost.Filesystem library\n" "and then run the given lua file.\n\n" "usage: filesystem filename [args]\n"; return 1; } using namespace luabind; open(L); bind_filesystem(L); object args = newtable(L); for (int i = 0; i < argc; ++i) { args[i + 1] = argv[i]; } args["n"] = argc; globals(L)["args"] = args; luaL_dofile(L, argv[1]); } luabind-1.1.1/examples/filesystem/inspect.lua000077500000000000000000000102051366245310300213060ustar00rootroot00000000000000-- base class for all inspectors -- every derived class must implement inspect() class 'inspector' function inspector:__init(name) self.name = name self.warnings = {} end function inspector:warning(path, str) table.insert( self.warnings, { path, str } ) end function inspector:report() local output = function(_,x) local name = x[1]:string() print(name .. ": " .. x[2]) end local cmp = function(a,b) return a[1]:string() < b[1]:string() end local violations if table.getn(self.warnings) ~= 0 then violations = table.getn(self.warnings) .. " violations" else violations = "no violations" end print("\n-- " .. self.name .. " [" .. violations .. "]\n") table.sort(self.warnings, cmp) table.foreach(self.warnings, output) end inspector.inspect = nil -- checks filename length class 'filename_length' (inspector) function filename_length:__init(n) super("filename length (" .. n .. " characters)") self.maxlen = n end function filename_length:inspect(path) local n = string.len(path:leaf()) if n > self.maxlen then self:warning(path, n .. " characters in filename") end end -- checks that the filename is all lowercase class 'filename_case' (inspector) function filename_case:__init() super("filename case") end function filename_case:inspect(path) if string.lower(path:leaf()) ~= path:leaf() then self:warning(path, "uppercase letters") end end -- checks that the file doesn't contain tabs class 'tab_inspector' (inspector) function tab_inspector:__init() super("tab inspector") end function tab_inspector:inspect(path) if has_endings(path:leaf(), ".hpp", ".cpp") then for line in io.lines(path:string()) do if string.find(line, '\t') ~= nil then self:warning(path, "tabs in file") return end end end end -- checks that the file doesn't contain too long lines class 'line_length_inspector' (inspector) function line_length_inspector:__init(n) super("line length inspector (" .. n .. " characters)") self.maxlen = n end function line_length_inspector:inspect(path) if has_endings(path:leaf(), ".hpp", ".cpp") then for line in io.lines(path:string()) do if string.len(line) > self.maxlen then self:warning(path, "lines too long " .. string.len(line)) return end end end end -- checks for unmatched #define/#undef pairs class 'define_inspector' (inspector) function define_inspector:__init() super("define inspector") end function define_inspector:inspect(path) if has_endings(path:leaf(), ".hpp") then local defs = {} for line in io.lines(path:string()) do local pos, _, def = string.find(line, "#%s*define%s+([%w_]+)") if pos ~= nil then defs[def] = true end local pos, _, def = string.find(line, "#%s*undef%s+([%w_]+)") if pos ~= nil then defs[def] = nil end end table.foreach(defs, function(def) self:warning(path, def) end) end end -- helper functions function file_ending(name) local pos = string.find(name, "%.") if pos == nil then return "" else return string.sub(name, pos) end end function has_endings(name, ...) local ending = file_ending(name) for _,i in arg do if ending == i then return true end end return false end function recurse_dir(path) for i in path.contents do if i:is_directory() then recurse_dir(i) else table.foreach(inspectors, function(_,x) x:inspect(i) end) number_of_files = number_of_files + 1 end end end -- main inspectors = { filename_length(31), filename_case(), tab_inspector(), line_length_inspector(79), define_inspector() } number_of_files = 0 if args.n >= 3 then root = filesystem.path(args[3]) else root = filesystem.initial_path() end print("inspecting '" .. root:string() .. "' ...") recurse_dir(root) print(" ** " .. number_of_files .. " files was inspected") table.foreach(inspectors, function(_,i) i:report() end) luabind-1.1.1/examples/glut/000077500000000000000000000000001366245310300157245ustar00rootroot00000000000000luabind-1.1.1/examples/glut/Jamfile000077500000000000000000000003261366245310300172220ustar00rootroot00000000000000import modules ; lib glut : : glut ; lib glu : : glu ; lib gl : : gl ; exe glut_bind : glut_bind.cpp gl glu glut /luabind//lualib /luabind//luabind ; stage . : glut_bind ; luabind-1.1.1/examples/glut/glut_bind.cpp000066400000000000000000000105061366245310300204010ustar00rootroot00000000000000extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } #include #include #include #include #include #include #include struct glut_constants {}; struct gl_constants {}; using luabind::object; namespace glut_bindings { object displayfunc; void displayfunc_callback() { displayfunc(); } void set_displayfunc(object const& fun) { glutDisplayFunc(&displayfunc_callback); displayfunc = fun; } object idlefunc; void idlefunc_callback() { idlefunc(); } void set_idlefunc(object const& fun) { glutIdleFunc(&idlefunc_callback); idlefunc = fun; } object reshapefunc; void reshapefunc_callback(int w, int h) { reshapefunc(w, h); } void set_reshapefunc(object const& fun) { reshapefunc = fun; } object keyboardfunc; void keyboardfunc_callback(unsigned char key, int x, int y) { keyboardfunc(key, x, y); } void set_keyboardfunc(object const& fun) { glutKeyboardFunc(&keyboardfunc_callback); keyboardfunc = fun; } object mousefunc; void mousefunc_callback(int button, int state, int x, int y) { mousefunc(button, state, x, y); } void set_mousefunc(object const& fun) { mousefunc = fun; } } void bind_glut(lua_State* L) { using namespace luabind; using namespace glut_bindings; open(L); module(L) [ def("glutInitWindowSize", &glutInitWindowSize), def("glutInitWindowPosition", &glutInitWindowPosition), def("glutInitDisplayMode", &glutInitDisplayMode), class_("glut") .enum_("constants") [ value("RGB", GLUT_RGB), value("RGBA", GLUT_RGBA), value("INDEX", GLUT_INDEX), value("SINGLE", GLUT_SINGLE), value("DOUBLE", GLUT_DOUBLE), value("DEPTH", GLUT_DEPTH), value("STENCIL", GLUT_STENCIL), value("LEFT_BUTTON", GLUT_LEFT_BUTTON), value("MIDDLE_BUTTON", GLUT_MIDDLE_BUTTON), value("RIGHT_BUTTON", GLUT_RIGHT_BUTTON), value("UP", GLUT_UP), value("DOWN", GLUT_DOWN), value("ELAPSED_TIME", GLUT_ELAPSED_TIME) ], def("glutCreateWindow", &glutCreateWindow), def("glutDestroyWindow", &glutDestroyWindow), def("glutFullScreen", &glutFullScreen), def("glutDisplayFunc", &set_displayfunc), def("glutKeyboardFunc", &set_keyboardfunc), def("glutReshapeFunc", &set_reshapefunc), def("glutIdleFunc", &set_idlefunc), def("glutMainLoop", &glutMainLoop), def("glutSwapBuffers", &glutSwapBuffers), def("glutGet", &glutGet), def("glutSolidSphere", &glutSolidSphere), def("glutWireSphere", &glutWireSphere), def("glutWireTeapot", &glutWireTeapot), def("glutSolidTeapot", &glutSolidTeapot), // -- opengl class_("gl") .enum_("constants") [ value("COLOR_BUFFER_BIT", GL_COLOR_BUFFER_BIT), value("DEPTH_BUFFER_BIT", GL_DEPTH_BUFFER_BIT), value("TRIANGLES", GL_TRIANGLES), value("MODELVIEW", GL_MODELVIEW), value("PROJECTION", GL_PROJECTION) ], def("glBegin", &glBegin), def("glVertex3", &glVertex3f), def("glEnd", &glEnd), def("glClear", &glClear), def("glPushMatrix", &glPushMatrix), def("glPopMatrix", &glPopMatrix), def("glRotate", &glRotatef), def("glColor3", &glColor3f), def("glColor4", &glColor4f), def("glMatrixMode", &glMatrixMode), def("glLoadIdentity", &glLoadIdentity), def("glViewport", &glViewport), def("glTranslate", &glTranslatef), // -- glu def("gluPerspective", &gluPerspective) ]; } int main(int argc, char* argv[]) { lua_State* L = luaL_newstate(); lua_baselibopen(L); lua_mathlibopen(L); bind_glut(L); glutInit (&argc, argv); lua_dofile(L, "glut_bindings.lua"); lua_close(L); return 0; } luabind-1.1.1/examples/glut/glut_bindings.lua000066400000000000000000000031601366245310300212570ustar00rootroot00000000000000quit = false function resize_func(w, h) local ratio = w / h print('====== resize') glMatrixMode(gl.PROJECTION) glLoadIdentity() glViewport(0,0,w,h) gluPerspective(45,ratio,1,1000) glMatrixMode(gl.MODELVIEW) glLoadIdentity() end angle = 0 angle2 = 0 previous_time = 0 function display_func() if quit then return end local cur_time = glutGet(glut.ELAPSED_TIME) local delta = (cur_time - previous_time) / 1000 previous_time = cur_time glClear(gl.COLOR_BUFFER_BIT + gl.DEPTH_BUFFER_BIT) glPushMatrix() glTranslate(0,0,-5) glRotate(angle, 0, 1, 0) glRotate(angle2, 0, 0, 1) glColor3(1,0,0) -- glutWireSphere(0.75, 10, 10) glutSolidTeapot(0.75) -- glColor3(1,1,1) -- glutWireTeapot(0.75) glPopMatrix() angle = angle + 200 * delta angle2 = angle2 + 170 * delta frames = frames + 1 if math.mod(frames, 100) == 0 then local fps = frames * 1000 / (glutGet(glut.ELAPSED_TIME) - start_time); print('fps: ' .. fps .. ' time: ' .. glutGet(glut.ELAPSED_TIME) .. ' frames: ' .. frames) end glutSwapBuffers() end function keyboard_func(key,x,y) print('keyboard' .. key) if key == 27 then glutDestroyWindow(window) quit = true end end glutInitWindowSize(600,600) glutInitWindowPosition(0,0) glutInitDisplayMode(glut.RGB + glut.DOUBLE + glut.DEPTH) window = glutCreateWindow("luabind, glut-bindings") glutDisplayFunc(display_func) glutIdleFunc(display_func) glutKeyboardFunc(keyboard_func) glutReshapeFunc(resize_func) resize_func(600,600) start_time = glutGet(glut.ELAPSED_TIME) frames = 0 glutMainLoop() luabind-1.1.1/examples/hello_world/000077500000000000000000000000001366245310300172635ustar00rootroot00000000000000luabind-1.1.1/examples/hello_world/Jamfile000077500000000000000000000002421366245310300205560ustar00rootroot00000000000000import modules ; use-project /luabind : ../../ ; lib hello_world : hello_world.cpp /luabind//luabind/static /luabind//lua ; stage . : hello_world ; luabind-1.1.1/examples/hello_world/README000066400000000000000000000004071366245310300201440ustar00rootroot00000000000000this example will build an extension module as a shared library, use loadlib() from within the lua interpreter to load the library, it will then export a function named greet() which you can call. > loadlib('hello_world.dll', 'init')() > greet() Hello world! > luabind-1.1.1/examples/hello_world/hello_world.cpp000077500000000000000000000027021366245310300223050ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin and Arvid Norberg // 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. extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } #include #include 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; } luabind-1.1.1/examples/hello_world/project-root.jam000066400000000000000000000000001366245310300223710ustar00rootroot00000000000000luabind-1.1.1/examples/intrusive_ptr/000077500000000000000000000000001366245310300176665ustar00rootroot00000000000000luabind-1.1.1/examples/intrusive_ptr/Jamfile000077500000000000000000000001661366245310300211660ustar00rootroot00000000000000import modules ; exe intrusive_ptr : intrusive_ptr.cpp /luabind//luabind ; stage . : intrusive_ptr ; luabind-1.1.1/examples/intrusive_ptr/intrusive_ptr.cpp000066400000000000000000000105561366245310300233160ustar00rootroot00000000000000#include extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } bool dostring(lua_State* L, const char* str) { if (luaL_loadbuffer(L, str, std::strlen(str), str) || lua_pcall(L, 0, 0, 0)) { const char* a = lua_tostring(L, -1); std::cout << a << "\n"; lua_pop(L, 1); return true; } return false; } #include #include namespace luabind { namespace converters { // tell luabind that there is a converter for boost::intrusive_ptr template yes_t is_user_defined(by_value >); template yes_t is_user_defined(by_const_reference >); // function used to destruct the object in lua template struct decrement_ref_count { static void apply(void* ptr) { T* p = static_cast(ptr); intrusive_ptr_release(p); } }; template void convert_cpp_to_lua(lua_State* L, const boost::intrusive_ptr& ptr) { if (!ptr) { lua_pushnil(L); return; } T* raw_ptr = ptr.get(); // add reference to object, this will be released when the object is collected intrusive_ptr_add_ref(raw_ptr); detail::class_registry* registry = luabind::detail::class_registry::get_registry(L); detail::class_rep* crep = registry->find_class(LUABIND_TYPEID(T)); assert(crep != 0 && "You are trying to convert an unregistered type"); // create the struct to hold the object void* obj = lua_newuserdata(L, sizeof(detail::object_rep)); // we send 0 as destructor since we know it will never be called new(obj) luabind::detail::object_rep(raw_ptr, crep, detail::object_rep::owner, decrement_ref_count::apply); // set the meta table detail::getref(L, crep->metatable_ref()); lua_setmetatable(L, -2); } template boost::intrusive_ptr convert_lua_to_cpp(lua_State* L, by_const_reference >, int index) { typename detail::default_policy::template generate_converter::type converter; T* ptr = converter.apply(L, LUABIND_DECORATE_TYPE(T*), index); return boost::intrusive_ptr(ptr); } template boost::intrusive_ptr convert_lua_to_cpp(lua_State* L, by_value >, int index) { return convert_lua_to_cpp(L, by_const_reference >(), index); } template int match_lua_to_cpp(lua_State* L, by_value >, int index) { typedef typename detail::default_policy::template generate_converter::type converter_t; return converter_t::match(L, LUABIND_DECORATE_TYPE(T*), index); } template int match_lua_to_cpp(lua_State* L, by_const_reference >, int index) { typedef typename detail::default_policy::template generate_converter::type converter_t; return converter_t::match(L, LUABIND_DECORATE_TYPE(T*), index); } } } struct A { A() : cnt(0) {} ~A() { std::cout << "free memory\n"; } int cnt; }; void intrusive_ptr_add_ref(A* ptr) { ++ptr->cnt; std::cout << "add ref\n"; } void intrusive_ptr_release(A* ptr) { --ptr->cnt; std::cout << "release\n"; if (ptr->cnt == 0) delete ptr; } void f(boost::intrusive_ptr ptr) { std::cout << "count: " << ptr->cnt << "\n"; } boost::intrusive_ptr factory() { return boost::intrusive_ptr(new A()); } int main() { lua_State* L = luaL_newstate(); lua_baselibopen(L); luabind::open(L); using namespace luabind; module(L) [ class_("A") .def_readonly("cnt", &A::cnt), def("factory", &factory), def("f", &f) ]; dostring(L, "a = factory()"); dostring(L, "print('lua count: ' .. a.cnt)"); dostring(L, "f(a)"); lua_close(L); return 0; } luabind-1.1.1/examples/regexp/000077500000000000000000000000001366245310300162435ustar00rootroot00000000000000luabind-1.1.1/examples/regexp/Jamfile000077500000000000000000000003221366245310300175350ustar00rootroot00000000000000import modules ; BOOST_ROOT = [ modules.peek : BOOST_ROOT ] ; use-project /boost : $(BOOST_ROOT) ; exe regexp : regex_wrap.cpp /boost/regex//boost_regex/static /luabind//luabind ; luabind-1.1.1/examples/regexp/regex.lua000066400000000000000000000003611366245310300200600ustar00rootroot00000000000000 html_tag = regex("<(.*?)>") src = 'dadasdsa' while html_tag:search(src) do print('tag: ' .. html_tag:what(1)) src = string.sub(src, html_tag:position(0) + html_tag:length(0)) end print('-------------') luabind-1.1.1/examples/regexp/regex_wrap.cpp000066400000000000000000000020141366245310300211070ustar00rootroot00000000000000#include extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } #include namespace { bool match(boost::RegEx& r, const char* s) { return r.Match(s); } bool search(boost::RegEx& r, const char* s) { return r.Search(s); } } // namespace unnamed void wrap_regex(lua_State* L) { using boost::RegEx; using namespace luabind; module(L) [ class_("regex") .def(constructor()) .def(constructor()) .def("match", match) .def("search", search) .def("what", &RegEx::What) .def("matched", &RegEx::Matched) .def("length", &RegEx::Length) .def("position", &RegEx::Position) ]; } int main() { lua_State* L = luaL_newstate(); lua_baselibopen(L); lua_strlibopen(L); luabind::open(L); wrap_regex(L); lua_dofile(L, "regex.lua"); lua_close(L); } luabind-1.1.1/get-deps.sh000077500000000000000000000007111366245310300152010ustar00rootroot00000000000000#!/bin/sh set -ex LUAV="$1" curl -o lua-$LUAV.tar.gz https://www.lua.org/ftp/lua-$LUAV.tar.gz tar xzf lua-$LUAV.tar.gz cd lua-$LUAV if [ "$2" = "cxx" ]; then if [ -d cxx ]; then rm -r cxx fi mkdir cxx make clean make linux CC=g++ MYCFLAGS="-DLUA_USE_APICHECK -g" mv src/lua src/luac src/liblua.a cxx/ cp src/lua.h src/luaconf.h src/lauxlib.h src/lualib.h cxx/ fi make clean make linux MYCFLAGS="-DLUA_USE_APICHECK -g" luabind-1.1.1/luabind/000077500000000000000000000000001366245310300145515ustar00rootroot00000000000000luabind-1.1.1/luabind/adopt_policy.hpp000066400000000000000000000117431366245310300177560ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_ADOPT_POLICY_HPP_INCLUDED #define LUABIND_ADOPT_POLICY_HPP_INCLUDED #include #include #include #include #include namespace luabind { namespace detail { template void adjust_backref_ownership(T* ptr, mpl::true_) { if (wrap_base* p = dynamic_cast(ptr)) { wrapped_self_t& wrapper = wrap_access::ref(*p); wrapper.get(wrapper.state()); wrapper.m_strong_ref.pop(wrapper.state()); } } inline void adjust_backref_ownership(void*, mpl::false_) {} template struct adopt_pointer : pointer_converter { typedef adopt_pointer type; int consumed_args() const { return 1; } template T* apply(lua_State* L, by_pointer, int index) { T* ptr = pointer_converter::apply( L, LUABIND_DECORATE_TYPE(T*), index); object_rep* obj = static_cast( lua_touserdata(L, index)); if (obj) { obj->release(); } adjust_backref_ownership(ptr, boost::is_polymorphic()); return ptr; } template int match(lua_State* L, by_pointer, int index) { return pointer_converter::match( L, LUABIND_DECORATE_TYPE(T*), index); } template void converter_postcall(lua_State*, T, int) {} }; template struct pointer_or_default { typedef Pointer type; }; template struct pointer_or_default { #ifdef LUABIND_USE_CXX11 typedef std::unique_ptr type; #else typedef std::auto_ptr type; #endif }; template struct adopt_pointer { typedef adopt_pointer type; template void apply(lua_State* L, T* ptr) { if (ptr == 0) { lua_pushnil(L); return; } // if there is a back_reference, then the // ownership will be removed from the // back reference and put on the lua stack. if (luabind::move_back_reference(L, ptr)) return; typedef typename pointer_or_default::type pointer_type; make_instance(L, pointer_type(ptr)); } }; template struct adopt_policy : conversion_policy { // BOOST_STATIC_CONSTANT(int, index = N); static void precall(lua_State*, const index_map&) {} static void postcall(lua_State*, const index_map&) {} struct only_accepts_nonconst_pointers {}; template struct apply { typedef luabind::detail::is_nonconst_pointer is_nonconst_p; typedef typename boost::mpl::if_< is_nonconst_p , adopt_pointer , only_accepts_nonconst_pointers >::type type; }; }; }} namespace luabind { template detail::policy_cons, detail::null_type> adopt(LUABIND_PLACEHOLDER_ARG(N)) { return detail::policy_cons, detail::null_type>(); } template detail::policy_cons, detail::null_type> adopt(LUABIND_PLACEHOLDER_ARG(N)) { return detail::policy_cons, detail::null_type>(); } } #endif // LUABIND_ADOPT_POLICY_HPP_INCLUDE luabind-1.1.1/luabind/back_reference.hpp000066400000000000000000000060471366245310300202070ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_BACK_REFERENCE_040510_HPP #define LUABIND_BACK_REFERENCE_040510_HPP #include #include #include #include #include #include namespace luabind { struct wrap_base; namespace detail { namespace mpl = boost::mpl; template wrap_base const* get_back_reference_aux0(T const* p, mpl::true_) { return dynamic_cast(p); } template wrap_base const* get_back_reference_aux0(T const*, mpl::false_) { return 0; } template wrap_base const* get_back_reference_aux1(T const* p) { return get_back_reference_aux0(p, boost::is_polymorphic()); } template wrap_base const* get_back_reference_aux2(T const& x, mpl::true_) { return get_back_reference_aux1(get_pointer(x)); } template wrap_base const* get_back_reference_aux2(T const& x, mpl::false_) { return get_back_reference_aux1(&x); } template wrap_base const* get_back_reference(T const& x) { return detail::get_back_reference_aux2( x , has_get_pointer() ); } } // namespace detail template bool get_back_reference(lua_State* L, T const& x) { if (wrap_base const* w = detail::get_back_reference(x)) { detail::wrap_access::ref(*w).get(L); return true; } return false; } template bool move_back_reference(lua_State* L, T const& x) { if (wrap_base* w = const_cast(detail::get_back_reference(x))) { assert(detail::wrap_access::ref(*w).m_strong_ref.is_valid()); detail::wrap_access::ref(*w).get(L); detail::wrap_access::ref(*w).m_strong_ref.reset(); return true; } return false; } } // namespace luabind #endif // LUABIND_BACK_REFERENCE_040510_HPP luabind-1.1.1/luabind/back_reference_fwd.hpp000066400000000000000000000027271366245310300210500ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_BACK_REFERENCE_FWD_040510_HPP #define LUABIND_BACK_REFERENCE_FWD_040510_HPP #include namespace luabind { template bool get_back_reference(lua_State* L, T const& x); template bool move_back_reference(lua_State* L, T const& x); } // namespace luabind #endif // LUABIND_BACK_REFERENCE_FWD_040510_HPP luabind-1.1.1/luabind/class.hpp000066400000000000000000000655421366245310300164030ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_CLASS_HPP_INCLUDED #define LUABIND_CLASS_HPP_INCLUDED /* ISSUES: ------------------------------------------------------ * solved for member functions, not application operator * if we have a base class that defines a function a derived class must be able to override that function (not just overload). Right now we just add the other overload to the overloads list and will probably get an ambiguity. If we want to support this each method_rep must include a vector of type_info pointers for each parameter. Operators do not have this problem, since operators always have to have it's own type as one of the arguments, no ambiguity can occur. Application operator, on the other hand, would have this problem. Properties cannot be overloaded, so they should always be overridden. If this is to work for application operator, we really need to specify if an application operator is const or not. If one class registers two functions with the same name and the same signature, there's currently no error. The last registered function will be the one that's used. How do we know which class registered the function? If the function was defined by the base class, it is a legal operation, to override it. we cannot look at the pointer offset, since it always will be zero for one of the bases. TODO: ------------------------------------------------------ finish smart pointer support * the adopt policy should not be able to adopt pointers to held_types. This must be prohibited. * name_of_type must recognize holder_types and not return "custom" document custom policies, custom converters store the instance object for policies. support the __concat metamethod. This is a bit tricky, since it cannot be treated as a normal operator. It is a binary operator but we want to use the __tostring implementation for both arguments. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // to remove the 'this' used in initialization list-warning #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4355) #endif namespace boost { template class shared_ptr; } // namespace boost namespace luabind { namespace detail { struct unspecified {}; template struct operator_; } template struct class_; template < BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT( LUABIND_MAX_BASES, class A, detail::null_type) > struct bases {}; typedef bases no_bases; namespace detail { template struct is_bases : mpl::false_ {}; template struct is_bases > : mpl::true_ {}; template struct is_unspecified : mpl::apply1 {}; template struct is_unspecified : mpl::true_ {}; template struct is_unspecified_mfn { template struct apply : is_unspecified {}; }; template struct get_predicate { typedef mpl::protect > type; }; template struct result_or_default { typedef Result type; }; template struct result_or_default { typedef Default type; }; template struct extract_parameter { typedef typename get_predicate::type pred; typedef typename boost::mpl::find_if::type iterator; typedef typename result_or_default< typename iterator::type, DefaultValue >::type type; }; struct LUABIND_API create_class { static int stage1(lua_State* L); static int stage2(lua_State* L); }; } // detail namespace detail { template struct static_scope { static_scope(T& self_) : self(self_) { } T& operator[](scope s) const { self.add_inner_scope(s); return self; } private: template void operator,(U const&) const; void operator=(static_scope const&); T& self; }; struct class_registration; struct LUABIND_API class_base : scope { public: class_base(char const* name); void init( type_id const& type, class_id id , type_id const& wrapped_type, class_id wrapper_id); void add_base(type_id const& base); void add_member(registration* member); void add_default_member(registration* member); const char* name() const; void add_static_constant(const char* name, int val); void add_inner_scope(scope& s); void add_cast(class_id src, class_id target, cast_function cast); private: class_registration* m_registration; }; // MSVC complains about member being sensitive to alignment (C4121) // when F is a pointer to member of a class with virtual bases. # ifdef BOOST_MSVC # pragma pack(push) # pragma pack(16) # endif template struct memfun_registration : registration { memfun_registration(char const* name_, F f_, Policies const& policies_) : name(name_) , f(f_) , policies(policies_) {} void register_(lua_State* L) const { object fn = make_function( L, f, deduce_signature(f, static_cast(0)), policies); add_overload( object(from_stack(L, -1)) , name , fn ); } char const* name; F f; Policies policies; }; # ifdef BOOST_MSVC # pragma pack(pop) # endif template struct default_pointer { typedef P type; }; template struct default_pointer { #ifdef LUABIND_USE_CXX11 typedef std::unique_ptr type; #else typedef std::auto_ptr type; #endif }; template struct constructor_registration : registration { constructor_registration(Policies const& policies_) : policies(policies_) {} void register_(lua_State* L) const { typedef typename default_pointer::type pointer; object fn = make_function( L , construct(), Signature() , policies ); add_overload( object(from_stack(L, -1)) , "__init" , fn ); } Policies policies; }; template struct reference_result : mpl::if_< mpl::or_, is_primitive > , T , typename boost::add_reference::type > {}; template struct reference_argument : mpl::if_< mpl::or_, is_primitive > , T , typename boost::add_reference< typename boost::add_const::type >::type > {}; template struct inject_dependency_policy : mpl::if_< mpl::or_< is_primitive , has_policy > , Policies , policy_cons, Policies> > {}; template < class Class , class Get, class GetPolicies , class Set = null_type, class SetPolicies = null_type > struct property_registration : registration { property_registration( char const* name_ , Get const& get_ , GetPolicies const& get_policies_ , Set const& set_ = Set() , SetPolicies const& set_policies_ = SetPolicies() ) : set(set_) , set_policies(set_policies_) , get(get_) , get_policies(get_policies_) , name(name_) {} void register_(lua_State* L) const { object context(from_stack(L, -1)); register_aux( L , context , make_get(L, get, boost::is_member_object_pointer()) , set ); } template object make_get(lua_State* L, F const& f, mpl::false_) const { return make_function( L, f, deduce_signature(f, static_cast(0)), get_policies); } template object make_get(lua_State* L, D T::* mem_ptr, mpl::true_) const { typedef typename reference_result::type result_type; typedef typename inject_dependency_policy< D, GetPolicies>::type policies; return make_function( L , access_member_ptr(mem_ptr) , mpl::vector2() , policies() ); } template object make_set(lua_State* L, F const& f, mpl::false_) const { return make_function( L, f, deduce_signature(f, static_cast(0)), set_policies); } template object make_set(lua_State* L, D T::* mem_ptr, mpl::true_) const { typedef typename reference_argument::type argument_type; return make_function( L , access_member_ptr(mem_ptr) , mpl::vector3() , set_policies ); } template void register_aux( lua_State* L, object const& context , object const& get_, S const&) const { context[name] = property( get_ , make_set(L, set, boost::is_member_object_pointer()) ); } void register_aux( lua_State*, object const& context , object const& get_, null_type) const { context[name] = property(get_); } Set set; SetPolicies set_policies; Get get; GetPolicies get_policies; char const* name; }; } // namespace detail // registers a class in the lua environment template struct class_: detail::class_base { typedef class_ self_t; private: template class_(const class_&); public: typedef boost::mpl::vector4 parameters_type; // WrappedType MUST inherit from T typedef typename detail::extract_parameter< parameters_type , boost::is_base_and_derived , detail::null_type >::type WrappedType; typedef typename detail::extract_parameter< parameters_type , boost::mpl::not_< boost::mpl::or_< detail::is_bases , boost::is_base_and_derived , boost::is_base_and_derived > > , detail::null_type >::type HeldType; template void add_downcast(Src*, Target*, boost::mpl::true_) { add_cast( detail::registered_class::id , detail::registered_class::id , detail::dynamic_cast_::execute ); } template void add_downcast(Src*, Target*, boost::mpl::false_) {} // this function generates conversion information // in the given class_rep structure. It will be able // to implicitly cast to the given template type template void gen_base_info(detail::type_) { add_base(typeid(To)); add_cast( detail::registered_class::id , detail::registered_class::id , detail::static_cast_::execute ); add_downcast(static_cast(0), static_cast(0), boost::is_polymorphic()); } void gen_base_info(detail::type_) {} #define LUABIND_GEN_BASE_INFO(z, n, text) gen_base_info(detail::type_()); template void generate_baseclass_list(detail::type_ >) { BOOST_PP_REPEAT(LUABIND_MAX_BASES, LUABIND_GEN_BASE_INFO, _) } #undef LUABIND_GEN_BASE_INFO class_(const char* name_ = 0): class_base(name_), scope(*this) { #ifndef NDEBUG detail::check_link_compatibility(); #endif init(); } template class_& def(const char* name_, F f) { return this->virtual_def( name_, f, detail::null_type() , detail::null_type(), boost::mpl::true_()); } // virtual functions template class_& def(char const* name_, F fn, DefaultOrPolicies default_or_policies) { return this->virtual_def( name_, fn, default_or_policies, detail::null_type() , typename detail::is_policy_cons::type()); } template class_& def(char const* name_, F fn , Default default_, Policies const& policies) { return this->virtual_def( name_, fn, default_ , policies, boost::mpl::false_()); } template class_& def(constructor sig) { return this->def_constructor(&sig, detail::null_type()); } template class_& def(constructor sig, const Policies& policies) { return this->def_constructor(&sig, policies); } template class_& property(const char* name_, Getter g) { this->add_member( new detail::property_registration( name_, g, detail::null_type())); return *this; } template class_& property(const char* name_, Getter g, MaybeSetter s) { return property_impl( name_, g, s , boost::mpl::bool_::value>() ); } template class_& property(const char* name_, Getter g, Setter s, const GetPolicies& get_policies) { typedef detail::property_registration< T, Getter, GetPolicies, Setter, detail::null_type > registration_type; this->add_member( new registration_type(name_, g, get_policies, s)); return *this; } template class_& property( const char* name_ , Getter g, Setter s , GetPolicies const& get_policies , SetPolicies const& set_policies) { typedef detail::property_registration< T, Getter, GetPolicies, Setter, SetPolicies > registration_type; this->add_member( new registration_type(name_, g, get_policies, s, set_policies)); return *this; } template class_& def_readonly(const char* name_, D C::*mem_ptr) { typedef detail::property_registration registration_type; this->add_member( new registration_type(name_, mem_ptr, detail::null_type())); return *this; } template class_& def_readonly(const char* name_, D C::*mem_ptr, Policies const& policies) { typedef detail::property_registration registration_type; this->add_member( new registration_type(name_, mem_ptr, policies)); return *this; } template class_& def_readwrite(const char* name_, D C::*mem_ptr) { typedef detail::property_registration< T, D C::*, detail::null_type, D C::* > registration_type; this->add_member( new registration_type( name_, mem_ptr, detail::null_type(), mem_ptr)); return *this; } template class_& def_readwrite( const char* name_, D C::*mem_ptr, GetPolicies const& get_policies) { typedef detail::property_registration< T, D C::*, GetPolicies, D C::* > registration_type; this->add_member( new registration_type( name_, mem_ptr, get_policies, mem_ptr)); return *this; } template class_& def_readwrite( const char* name_ , D C::*mem_ptr , GetPolicies const& get_policies , SetPolicies const& set_policies ) { typedef detail::property_registration< T, D C::*, GetPolicies, D C::*, SetPolicies > registration_type; this->add_member( new registration_type( name_, mem_ptr, get_policies, mem_ptr, set_policies)); return *this; } template class_& def(detail::operator_, Policies const& policies) { return this->def( Derived::name() , &Derived::template apply::execute , policies ); } template class_& def(detail::operator_) { return this->def( Derived::name() , &Derived::template apply::execute ); } detail::enum_maker enum_(const char*) { return detail::enum_maker(*this); } detail::static_scope scope; private: void operator=(class_ const&); void add_wrapper_cast(detail::null_type*) {} template void add_wrapper_cast(U*) { add_cast( detail::registered_class::id , detail::registered_class::id , detail::static_cast_::execute ); add_downcast(static_cast(0), static_cast(0), boost::is_polymorphic()); } void init() { typedef typename detail::extract_parameter< parameters_type , boost::mpl::or_< detail::is_bases , boost::is_base_and_derived > , no_bases >::type bases_t; typedef typename boost::mpl::if_ , bases_t , bases >::type Base; class_base::init( typeid(T) , detail::registered_class::id , typeid(WrappedType) , detail::registered_class::id ); add_wrapper_cast(static_cast(0)); generate_baseclass_list(detail::type_()); } template class_& property_impl(const char* name_, Getter g, GetPolicies policies, boost::mpl::bool_) { this->add_member( new detail::property_registration( name_, g, policies)); return *this; } template class_& property_impl(const char* name_, Getter g, Setter s, boost::mpl::bool_) { typedef detail::property_registration< T, Getter, detail::null_type, Setter, detail::null_type > registration_type; this->add_member( new registration_type(name_, g, detail::null_type(), s)); return *this; } // these handle default implementation of virtual functions template class_& virtual_def(char const* name_, F const& fn , Policies const&, detail::null_type, boost::mpl::true_) { this->add_member( new detail::memfun_registration( name_, fn, Policies())); return *this; } template class_& virtual_def(char const* name_, F const& fn , Default const& default_, Policies const&, boost::mpl::false_) { this->add_member( new detail::memfun_registration( name_, fn, Policies())); this->add_default_member( new detail::memfun_registration( name_, default_, Policies())); return *this; } template class_& def_constructor(Signature*, Policies const&) { typedef typename Signature::signature signature; typedef typename boost::mpl::if_< boost::is_same , T , WrappedType >::type construct_type; this->add_member( new detail::constructor_registration< construct_type, HeldType, signature, Policies>( Policies())); this->add_default_member( new detail::constructor_registration< construct_type, HeldType, signature, Policies>( Policies())); return *this; } }; } #ifdef _MSC_VER #pragma warning(pop) #endif #endif // LUABIND_CLASS_HPP_INCLUDED luabind-1.1.1/luabind/class_info.hpp000066400000000000000000000032501366245310300174020ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_CLASS_INFO_HPP_INCLUDED #define LUABIND_CLASS_INFO_HPP_INCLUDED #include #include #include #include namespace luabind { struct LUABIND_API class_info { std::string name; object methods; object attributes; }; LUABIND_API class_info get_class_info(argument const&); // returns a table of bound class names LUABIND_API object get_class_names(lua_State* L); LUABIND_API void bind_class_info(lua_State*); } #endif luabind-1.1.1/luabind/config.hpp000066400000000000000000000121601366245310300165270ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_CONFIG_HPP_INCLUDED #define LUABIND_CONFIG_HPP_INCLUDED #include #include #include #include #ifdef BOOST_MSVC #define LUABIND_ANONYMOUS_FIX static #else #define LUABIND_ANONYMOUS_FIX #endif #if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) #error "Support for your version of Visual C++ has been removed from this version of Luabind" #endif // the maximum number of arguments of functions that's // registered. Must at least be 2 #ifndef LUABIND_MAX_ARITY #define LUABIND_MAX_ARITY 10 #elif LUABIND_MAX_ARITY <= 1 #undef LUABIND_MAX_ARITY #define LUABIND_MAX_ARITY 2 #endif // the maximum number of classes one class // can derive from // max bases must at least be 1 #ifndef LUABIND_MAX_BASES #define LUABIND_MAX_BASES 4 #elif LUABIND_MAX_BASES <= 0 #undef LUABIND_MAX_BASES #define LUABIND_MAX_BASES 1 #endif // LUABIND_NO_ERROR_CHECKING // define this to remove all error checks // this will improve performance and memory // footprint. // if it is defined matchers will only be called on // overloaded functions, functions that's // not overloaded will be called directly. The // parameters on the lua stack are assumed // to match those of the function. // exceptions will still be catched when there's // no error checking. // LUABIND_NOT_THREADSAFE // this define will make luabind non-thread safe. That is, // it will rely on a static variable. You can still have // multiple lua states and use coroutines, but only // one of your real threads may run lua code. // LUABIND_NO_EXCEPTIONS // this define will disable all usage of try, catch and throw in // luabind. This will in many cases disable runtime-errors, such // as invalid casts, when calling lua-functions that fails or // returns values that cannot be converted by the given policy. // Luabind requires that no function called directly or indirectly // by luabind throws an exception (throwing exceptions through // C code has undefined behavior, lua is written in C). #ifdef LUABIND_DYNAMIC_LINK # if defined (BOOST_WINDOWS) # ifdef LUABIND_BUILDING # define LUABIND_API __declspec(dllexport) # else # define LUABIND_API __declspec(dllimport) # endif # elif defined (__CYGWIN__) # ifdef LUABIND_BUILDING # define LUABIND_API __attribute__ ((dllexport)) # else # define LUABIND_API __attribute__ ((dllimport)) # endif # else # if defined(__GNUC__) && __GNUC__ >=4 # define LUABIND_API __attribute__ ((visibility("default"))) # endif # endif #endif #ifndef LUABIND_API # define LUABIND_API #endif // C++11 features // #if ( defined(BOOST_NO_CXX11_SCOPED_ENUMS) \ || defined(BOOST_NO_SCOPED_ENUMS) \ || BOOST_VERSION < 105600 \ && ( defined(BOOST_NO_CXX11_HDR_TYPE_TRAITS) \ || defined(BOOST_NO_0X_HDR_TYPE_TRAITS))) # define LUABIND_NO_SCOPED_ENUM #endif #if ( defined(BOOST_NO_CXX11_RVALUE_REFERENCES) \ || defined(BOOST_NO_RVALUE_REFERENCES)) # define LUABIND_NO_RVALUE_REFERENCES #endif // If you use Boost <= 1.46 but your compiler is C++11 compliant and marks // destructors as noexcept by default, you need to define LUABIND_USE_NOEXCEPT. #if ( !defined(BOOST_NO_NOEXCEPT) \ && !defined(BOOST_NO_CXX11_NOEXCEPT) \ && BOOST_VERSION >= 104700) # define LUABIND_USE_NOEXCEPT #endif #ifndef LUABIND_MAY_THROW # ifdef BOOST_NOEXCEPT_IF # define LUABIND_MAY_THROW BOOST_NOEXCEPT_IF(false) # elif defined(LUABIND_USE_NOEXCEPT) # define LUABIND_MAY_THROW noexcept(false) # else # define LUABIND_MAY_THROW # endif #endif #ifndef LUABIND_NOEXCEPT # ifdef BOOST_NOEXCEPT_OR_NOTHROW # define LUABIND_NOEXCEPT BOOST_NOEXCEPT_OR_NOTHROW # elif defined(LUABIND_USE_NOEXCEPT) # define LUABIND_NOEXCEPT noexcept # else # define LUABIND_NOEXCEPT throw() # endif #endif namespace luabind { LUABIND_API void disable_super_deprecation(); } // namespace luabind #endif // LUABIND_CONFIG_HPP_INCLUDED luabind-1.1.1/luabind/container_policy.hpp000066400000000000000000000115271366245310300206310ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_CONTAINER_POLICY_HPP_INCLUDED #define LUABIND_CONTAINER_POLICY_HPP_INCLUDED #include #include // for LUABIND_DECORATE_TYPE #include // for policy_cons, etc #include // for null_type (ptr only), etc #include #include // for if_ #include // for is_same namespace luabind { namespace detail { namespace mpl = boost::mpl; template struct container_converter_lua_to_cpp { int consumed_args() const { return 1; } template T apply(lua_State* L, by_const_reference, int index) { typedef typename T::value_type value_type; typedef typename find_conversion_policy<1, Policies>::type converter_policy; typename mpl::apply_wrap2::type converter; T container; lua_pushnil(L); while (lua_next(L, index)) { container.push_back(converter.apply(L, LUABIND_DECORATE_TYPE(value_type), -1)); lua_pop(L, 1); // pop value } return container; } template T apply(lua_State* L, by_value, int index) { return apply(L, by_const_reference(), index); } template static int match(lua_State* L, by_const_reference, int index) { if (lua_istable(L, index)) return 0; else return -1; } template void converter_postcall(lua_State*, T, int) {} }; template struct container_converter_cpp_to_lua { template void apply(lua_State* L, const T& container) { typedef typename T::value_type value_type; typedef typename find_conversion_policy<1, Policies>::type converter_policy; typename mpl::apply_wrap2::type converter; lua_newtable(L); int index = 1; for (typename T::const_iterator i = container.begin(); i != container.end(); ++i) { converter.apply(L, *i); lua_rawseti(L, -2, index); ++index; } } }; template // struct container_policy : converter_policy_tag struct container_policy : conversion_policy { // BOOST_STATIC_CONSTANT(int, index = N); static void precall(lua_State*, const index_map&) {} static void postcall(lua_State*, const index_map&) {} struct only_accepts_nonconst_pointers {}; template struct apply { typedef typename boost::mpl::if_ , container_converter_lua_to_cpp , container_converter_cpp_to_lua >::type type; }; }; }} namespace luabind { template detail::policy_cons, detail::null_type> container(LUABIND_PLACEHOLDER_ARG(N)) { return detail::policy_cons, detail::null_type>(); } template detail::policy_cons, detail::null_type> container(LUABIND_PLACEHOLDER_ARG(N), const Policies&) { return detail::policy_cons, detail::null_type>(); } } #endif // LUABIND_CONTAINER_POLICY_HPP_INCLUDED luabind-1.1.1/luabind/copy_policy.hpp000066400000000000000000000024411366245310300176140ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_COPY_POLICY_081021_HPP # define LUABIND_COPY_POLICY_081021_HPP # include namespace luabind { namespace detail { struct copy_converter { template void apply(lua_State* L, T const& x) { value_converter().apply(L, x); } template void apply(lua_State* L, T* x) { if (!x) lua_pushnil(L); else apply(L, *x); } }; template struct copy_policy : conversion_policy { static void precall(lua_State*, index_map const&) {} static void postcall(lua_State*, index_map const&) {} template struct apply { typedef copy_converter type; }; }; } // namespace detail template detail::policy_cons, detail::null_type> copy(LUABIND_PLACEHOLDER_ARG(N)) { return detail::policy_cons, detail::null_type>(); } } // namespace luabind #endif // LUABIND_COPY_POLICY_081021_HPP luabind-1.1.1/luabind/dependency_policy.hpp000066400000000000000000000052031366245310300207570ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_DEPENDENCY_POLICY_HPP_INCLUDED #define LUABIND_DEPENDENCY_POLICY_HPP_INCLUDED #include #include // for object_rep #include // for policy_cons, etc #include // for null_type namespace luabind { namespace detail { // makes A dependent on B, meaning B will outlive A. // internally A stores a reference to B template struct dependency_policy { static void postcall(lua_State* L, const index_map& indices) { int nurse_index = indices[A]; int patient = indices[B]; object_rep* nurse = static_cast(lua_touserdata(L, nurse_index)); // If the nurse isn't an object_rep, just make this a nop. if (nurse == 0) return; nurse->add_dependency(L, patient); } }; }} namespace luabind { template detail::policy_cons, detail::null_type> dependency(LUABIND_PLACEHOLDER_ARG(A), LUABIND_PLACEHOLDER_ARG(B)) { return detail::policy_cons, detail::null_type>(); } template detail::policy_cons, detail::null_type> return_internal_reference(LUABIND_PLACEHOLDER_ARG(A)) { return detail::policy_cons, detail::null_type>(); } } #endif // LUABIND_DEPENDENCY_POLICY_HPP_INCLUDED luabind-1.1.1/luabind/detail/000077500000000000000000000000001366245310300160135ustar00rootroot00000000000000luabind-1.1.1/luabind/detail/call.hpp000066400000000000000000000217061366245310300174450ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !BOOST_PP_IS_ITERATING # ifndef LUABIND_CALL2_080911_HPP # define LUABIND_CALL2_080911_HPP # include # include # include # include # include # include # include # include # include # include # include # include # include # include # include # include # include namespace luabind { namespace detail { struct invoke_context; struct LUABIND_API function_object { function_object(lua_CFunction entry_) : entry(entry_) , next(0) {} virtual ~function_object() {} virtual int call( lua_State* L, invoke_context& ctx) const = 0; virtual void format_signature(lua_State* L, char const* function) const = 0; lua_CFunction entry; std::string name; function_object* next; object keepalive; }; struct LUABIND_API invoke_context { invoke_context() : best_score((std::numeric_limits::max)()) , candidate_index(0) , additional_candidates(0) {} operator bool() const { return candidate_index == 1; } void format_error(lua_State* L, function_object const* overloads) const; BOOST_STATIC_CONSTANT(int, max_candidates = 10); function_object const* candidates[max_candidates]; int best_score; int candidate_index; int additional_candidates; }; template inline int invoke0( lua_State* L, function_object const& self, invoke_context& ctx , F const& f, Signature, Policies const& policies, IsVoid, mpl::true_) { return invoke_member( L, self, ctx, f, Signature(), policies , mpl::long_::value - 1>(), IsVoid() ); } template inline int invoke0( lua_State* L, function_object const& self, invoke_context& ctx, F const& f, Signature, Policies const& policies, IsVoid, mpl::false_) { return invoke_normal( L, self, ctx, f, Signature(), policies , mpl::long_::value - 1>(), IsVoid() ); } template inline int invoke( lua_State* L, function_object const& self, invoke_context& ctx , F const& f, Signature, Policies const& policies) { return invoke0( L, self, ctx, f, Signature(), policies , boost::is_void::type>() , boost::is_member_function_pointer() ); } inline int maybe_yield_aux(int results, mpl::false_) { return results; } inline int maybe_yield_aux(int results, mpl::true_) { assert(results >= 0); return -results - 1; } template int maybe_yield(int results, Policies*) { return maybe_yield_aux( results, has_policy()); } inline int sum_scores(int const* first, int const* last) { int result = 0; for (; first != last; ++first) { if (*first < 0) return *first; result += *first; } return result; } # define LUABIND_INVOKE_NEXT_ITER(n) \ typename mpl::next< \ BOOST_PP_IF( \ n, BOOST_PP_CAT(iter,BOOST_PP_DEC(n)), first) \ >::type # define LUABIND_INVOKE_NEXT_INDEX(n) \ BOOST_PP_IF( \ n \ , BOOST_PP_CAT(index,BOOST_PP_DEC(n)) + \ BOOST_PP_CAT(c,BOOST_PP_DEC(n)).consumed_args() \ , 1 \ ) # define LUABIND_INVOKE_COMPUTE_ARITY(n) + BOOST_PP_CAT(c,n).consumed_args() # define LUABIND_INVOKE_DECLARE_CONVERTER(n) \ typedef LUABIND_INVOKE_NEXT_ITER(n) BOOST_PP_CAT(iter,n); \ typedef typename mpl::deref::type \ BOOST_PP_CAT(a,n); \ typedef typename find_conversion_policy::type \ BOOST_PP_CAT(p,n); \ typename mpl::apply_wrap2< \ BOOST_PP_CAT(p,n), BOOST_PP_CAT(a,n), lua_to_cpp>::type BOOST_PP_CAT(c,n); \ int const BOOST_PP_CAT(index,n) = LUABIND_INVOKE_NEXT_INDEX(n); # define LUABIND_INVOKE_COMPUTE_SCORE(n) \ , BOOST_PP_CAT(c,n).match( \ L, LUABIND_DECORATE_TYPE(BOOST_PP_CAT(a,n)), BOOST_PP_CAT(index,n)) # define LUABIND_INVOKE_ARG(z, n, base) \ BOOST_PP_CAT(c,base(n)).apply( \ L, LUABIND_DECORATE_TYPE(BOOST_PP_CAT(a,base(n))), BOOST_PP_CAT(index,base(n))) # define LUABIND_INVOKE_CONVERTER_POSTCALL(n) \ BOOST_PP_CAT(c,n).converter_postcall( \ L, LUABIND_DECORATE_TYPE(BOOST_PP_CAT(a,n)), BOOST_PP_CAT(index,n)); # define BOOST_PP_ITERATION_PARAMS_1 \ (3, (0, LUABIND_MAX_ARITY, )) # include BOOST_PP_ITERATE() # define LUABIND_INVOKE_VOID # define BOOST_PP_ITERATION_PARAMS_1 \ (3, (0, LUABIND_MAX_ARITY, )) # include BOOST_PP_ITERATE() # undef LUABIND_INVOKE_VOID # define LUABIND_INVOKE_MEMBER # define BOOST_PP_ITERATION_PARAMS_1 \ (3, (0, LUABIND_MAX_ARITY, )) # include BOOST_PP_ITERATE() # define LUABIND_INVOKE_VOID # define BOOST_PP_ITERATION_PARAMS_1 \ (3, (0, LUABIND_MAX_ARITY, )) # include BOOST_PP_ITERATE() }} // namespace luabind::detail # endif // LUABIND_CALL2_080911_HPP #else // BOOST_PP_IS_ITERATING # ifdef LUABIND_INVOKE_MEMBER # define N BOOST_PP_INC(BOOST_PP_ITERATION()) # else # define N BOOST_PP_ITERATION() # endif template inline int # ifdef LUABIND_INVOKE_MEMBER invoke_member # else invoke_normal # endif ( lua_State* L, function_object const& self, invoke_context& ctx , F const& f, Signature, Policies const&, mpl::long_ # ifdef LUABIND_INVOKE_VOID , mpl::true_ # else , mpl::false_ # endif ) { typedef typename mpl::begin::type first; # ifndef LUABIND_INVOKE_VOID typedef typename mpl::deref::type result_type; typedef typename find_conversion_policy<0, Policies>::type result_policy; typename mpl::apply_wrap2< result_policy, result_type, cpp_to_lua>::type result_converter; # endif # if N > 0 # define BOOST_PP_LOCAL_MACRO(n) LUABIND_INVOKE_DECLARE_CONVERTER(n) # define BOOST_PP_LOCAL_LIMITS (0,N-1) # include BOOST_PP_LOCAL_ITERATE() # endif int const arity = 0 # if N > 0 # define BOOST_PP_LOCAL_MACRO(n) LUABIND_INVOKE_COMPUTE_ARITY(n) # define BOOST_PP_LOCAL_LIMITS (0,N-1) # include BOOST_PP_LOCAL_ITERATE() # endif ; int const arguments = lua_gettop(L); int score = -1; if (arity == arguments) { int const scores[] = { 0 # if N > 0 # define BOOST_PP_LOCAL_MACRO(n) LUABIND_INVOKE_COMPUTE_SCORE(n) # define BOOST_PP_LOCAL_LIMITS (0,N-1) # include BOOST_PP_LOCAL_ITERATE() # endif }; score = sum_scores(scores + 1, scores + 1 + N); } if (score >= 0 && score < ctx.best_score) { ctx.best_score = score; ctx.candidates[0] = &self; ctx.candidate_index = 1; ctx.additional_candidates = 0; } else if (score == ctx.best_score) { if (ctx.candidate_index < invoke_context::max_candidates) ctx.candidates[ctx.candidate_index++] = &self; else ++ctx.additional_candidates; } int results = 0; if (self.next) { results = self.next->call(L, ctx); } if (score == ctx.best_score && ctx.candidate_index == 1) { # ifndef LUABIND_INVOKE_VOID result_converter.apply( L, # endif # ifdef LUABIND_INVOKE_MEMBER (c0.apply(L, LUABIND_DECORATE_TYPE(a0), index0).*f)( BOOST_PP_ENUM(BOOST_PP_DEC(N), LUABIND_INVOKE_ARG, BOOST_PP_INC) ) # else # define LUABIND_INVOKE_IDENTITY(x) x f( BOOST_PP_ENUM(N, LUABIND_INVOKE_ARG, LUABIND_INVOKE_IDENTITY) ) # undef LUABIND_INVOKE_IDENTITY # endif # ifndef LUABIND_INVOKE_VOID ) # endif ; # if N > 0 # define BOOST_PP_LOCAL_MACRO(n) LUABIND_INVOKE_CONVERTER_POSTCALL(n) # define BOOST_PP_LOCAL_LIMITS (0,N-1) # include BOOST_PP_LOCAL_ITERATE() # endif results = maybe_yield(lua_gettop(L) - arguments, (Policies*)0); if (results < 0) // We should yield. return results; int const indices[] = { arguments + results BOOST_PP_ENUM_TRAILING_PARAMS(N, index) }; policy_list_postcall::apply(L, indices); } return results; } # undef N #endif luabind-1.1.1/luabind/detail/call_function.hpp000066400000000000000000000444461366245310300213600ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #if !BOOST_PP_IS_ITERATING #ifndef LUABIND_CALL_FUNCTION_HPP_INCLUDED #define LUABIND_CALL_FUNCTION_HPP_INCLUDED #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace luabind { namespace detail { // if the proxy_function_caller returns non-void template class proxy_function_caller { // friend class luabind::object; public: typedef int(*function_t)(lua_State*, int, int); proxy_function_caller( lua_State* L , int params , function_t fun , const Tuple args) : m_args(args) , m_fun(fun) , m_state(L) , m_params(params) , m_called(false) { } proxy_function_caller(const proxy_function_caller& rhs) : m_args(rhs.m_args) , m_fun(rhs.m_fun) , m_state(rhs.m_state) , m_params(rhs.m_params) , m_called(rhs.m_called) { rhs.m_called = true; } ~proxy_function_caller() LUABIND_MAY_THROW { if (m_called) return; m_called = true; lua_State* L = m_state; int top = lua_gettop(L); push_args_from_tuple<1>::apply(L, m_args); if (m_fun(L, boost::tuples::length::value, 0)) { assert(lua_gettop(L) == top - m_params + 1); #ifndef LUABIND_NO_EXCEPTIONS throw luabind::error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." " If you want to handle the error you can use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function call stack_pop pop(L, lua_gettop(L) - top + m_params); } operator Ret() { typename mpl::apply_wrap2::type converter; m_called = true; lua_State* L = m_state; int top = lua_gettop(L); push_args_from_tuple<1>::apply(L, m_args); if (m_fun(L, boost::tuples::length::value, 1)) { assert(lua_gettop(L) == top - m_params + 1); #ifndef LUABIND_NO_EXCEPTIONS throw luabind::error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." " If you want to handle the error you can use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function call stack_pop pop(L, lua_gettop(L) - top + m_params); if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0) { #ifndef LUABIND_NO_EXCEPTIONS throw cast_failed(L, typeid(Ret)); #else cast_failed_callback_fun e = get_cast_failed_callback(); if (e) e(L, typeid(Ret)); assert(0 && "the lua function's return value could not be converted." " If you want to handle the error you can use luabind::set_error_callback()"); std::terminate(); #endif } return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1); } template Ret operator[](const Policies& p) { typedef typename detail::find_conversion_policy<0, Policies>::type converter_policy; typename mpl::apply_wrap2::type converter; m_called = true; lua_State* L = m_state; int top = lua_gettop(L); detail::push_args_from_tuple<1>::apply(L, m_args, p); if (m_fun(L, boost::tuples::length::value, 1)) { assert(lua_gettop(L) == top - m_params + 1); #ifndef LUABIND_NO_EXCEPTIONS throw error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." " If you want to handle the error you can use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function call stack_pop pop(L, lua_gettop(L) - top + m_params); if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0) { #ifndef LUABIND_NO_EXCEPTIONS throw cast_failed(L, typeid(Ret)); #else cast_failed_callback_fun e = get_cast_failed_callback(); if (e) e(L, typeid(Ret)); assert(0 && "the lua function's return value could not be converted." " If you want to handle the error you can use luabind::set_error_callback()"); std::terminate(); #endif } return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1); } private: Tuple m_args; function_t m_fun; lua_State* m_state; int m_params; mutable bool m_called; }; // if the proxy_member_caller returns void template class proxy_function_void_caller { friend class luabind::object; public: typedef int(*function_t)(lua_State*, int, int); proxy_function_void_caller( lua_State* L , int params , function_t fun , const Tuple args) : m_state(L) , m_params(params) , m_fun(fun) , m_args(args) , m_called(false) { } proxy_function_void_caller(const proxy_function_void_caller& rhs) : m_state(rhs.m_state) , m_params(rhs.m_params) , m_fun(rhs.m_fun) , m_args(rhs.m_args) , m_called(rhs.m_called) { rhs.m_called = true; } ~proxy_function_void_caller() LUABIND_MAY_THROW { if (m_called) return; m_called = true; lua_State* L = m_state; int top = lua_gettop(L); push_args_from_tuple<1>::apply(L, m_args); if (m_fun(L, boost::tuples::length::value, 0)) { assert(lua_gettop(L) == top - m_params + 1); #ifndef LUABIND_NO_EXCEPTIONS throw luabind::error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." " If you want to handle the error you can use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function call stack_pop pop(L, lua_gettop(L) - top + m_params); } template void operator[](const Policies& p) { m_called = true; lua_State* L = m_state; int top = lua_gettop(L); detail::push_args_from_tuple<1>::apply(L, m_args, p); if (m_fun(L, boost::tuples::length::value, 0)) { assert(lua_gettop(L) == top - m_params + 1); #ifndef LUABIND_NO_EXCEPTIONS throw error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." " If you want to handle the error you can use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function call stack_pop pop(L, lua_gettop(L) - top + m_params); } private: lua_State* m_state; int m_params; function_t m_fun; Tuple m_args; mutable bool m_called; }; } #define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LUABIND_MAX_ARITY, , 1)) #include BOOST_PP_ITERATE() } #endif // LUABIND_CALL_FUNCTION_HPP_INCLUDED #else #if BOOST_PP_ITERATION_FLAGS() == 1 #define LUABIND_TUPLE_PARAMS(z, n, data) const A##n * #define LUABIND_OPERATOR_PARAMS(z, n, data) const A##n & a##n template typename boost::mpl::if_ , luabind::detail::proxy_function_void_caller > , luabind::detail::proxy_function_caller > >::type call_function(lua_State* L, const char* name BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _) ) { assert(name && "luabind::call_function() expects a function name"); typedef boost::tuples::tuple tuple_t; #if BOOST_PP_ITERATION() == 0 tuple_t args; #else tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a)); #endif typedef typename boost::mpl::if_ , luabind::detail::proxy_function_void_caller > , luabind::detail::proxy_function_caller > >::type proxy_type; lua_getglobal(L, name); return proxy_type(L, 1, &detail::pcall, args); } template typename boost::mpl::if_ , luabind::detail::proxy_function_void_caller > , luabind::detail::proxy_function_caller > >::type call_function(luabind::object const& obj BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _) ) { typedef boost::tuples::tuple tuple_t; #if BOOST_PP_ITERATION() == 0 tuple_t args; #else tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a)); #endif typedef typename boost::mpl::if_ , luabind::detail::proxy_function_void_caller > , luabind::detail::proxy_function_caller > >::type proxy_type; obj.push(obj.interpreter()); return proxy_type(obj.interpreter(), 1, &detail::pcall, args); } template typename boost::mpl::if_ , luabind::detail::proxy_function_void_caller > , luabind::detail::proxy_function_caller > >::type resume_function(lua_State* L, const char* name BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _) ) { assert(name && "luabind::resume_function() expects a function name"); typedef boost::tuples::tuple tuple_t; #if BOOST_PP_ITERATION() == 0 tuple_t args; #else tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a)); #endif typedef typename boost::mpl::if_ , luabind::detail::proxy_function_void_caller > , luabind::detail::proxy_function_caller > >::type proxy_type; lua_getglobal(L, name); return proxy_type(L, 1, &detail::resume_impl, args); } template typename boost::mpl::if_ , luabind::detail::proxy_function_void_caller > , luabind::detail::proxy_function_caller > >::type resume_function(luabind::object const& obj BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _) ) { typedef boost::tuples::tuple tuple_t; #if BOOST_PP_ITERATION() == 0 tuple_t args; #else tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a)); #endif typedef typename boost::mpl::if_ , luabind::detail::proxy_function_void_caller > , luabind::detail::proxy_function_caller > >::type proxy_type; obj.push(obj.interpreter()); return proxy_type(obj.interpreter(), 1, &detail::resume_impl, args); } template typename boost::mpl::if_ , luabind::detail::proxy_function_void_caller > , luabind::detail::proxy_function_caller > >::type resume(lua_State* L BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _) ) { typedef boost::tuples::tuple tuple_t; #if BOOST_PP_ITERATION() == 0 tuple_t args; #else tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a)); #endif typedef typename boost::mpl::if_ , luabind::detail::proxy_function_void_caller > , luabind::detail::proxy_function_caller > >::type proxy_type; return proxy_type(L, 0, &detail::resume_impl, args); } #undef LUABIND_OPERATOR_PARAMS #undef LUABIND_TUPLE_PARAMS #endif #endif luabind-1.1.1/luabind/detail/call_member.hpp000066400000000000000000000326531366245310300207770ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #if !BOOST_PP_IS_ITERATING #ifndef LUABIND_CALL_MEMBER_HPP_INCLUDED #define LUABIND_CALL_MEMBER_HPP_INCLUDED #include #include #include #include #include #include // TODO: REMOVE DEPENDENCY #include #include #include #include #include namespace luabind { namespace detail { namespace mpl = boost::mpl; // if the proxy_member_caller returns non-void template class proxy_member_caller { // friend class luabind::object; public: proxy_member_caller(lua_State* L_, const Tuple args) : L(L_) , m_args(args) , m_called(false) { } proxy_member_caller(const proxy_member_caller& rhs) : L(rhs.L) , m_args(rhs.m_args) , m_called(rhs.m_called) { rhs.m_called = true; } ~proxy_member_caller() LUABIND_MAY_THROW { if (m_called) return; m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters push_args_from_tuple<1>::apply(L, m_args); if (pcall(L, boost::tuples::length::value + 1, 0)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw luabind::error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); } operator Ret() { typename mpl::apply_wrap2::type converter; m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters push_args_from_tuple<1>::apply(L, m_args); if (pcall(L, boost::tuples::length::value + 1, 1)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw luabind::error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw cast_failed(L, typeid(Ret)); #else cast_failed_callback_fun e = get_cast_failed_callback(); if (e) e(L, typeid(Ret)); assert(0 && "the lua function's return value could not be converted." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1); } template Ret operator[](const Policies& p) { typedef typename find_conversion_policy<0, Policies>::type converter_policy; typename mpl::apply_wrap2::type converter; m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters detail::push_args_from_tuple<1>::apply(L, m_args, p); if (pcall(L, boost::tuples::length::value + 1, 1)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw cast_failed(L, typeid(Ret)); #else cast_failed_callback_fun e = get_cast_failed_callback(); if (e) e(L, typeid(Ret)); assert(0 && "the lua function's return value could not be converted." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1); } private: lua_State* L; Tuple m_args; mutable bool m_called; }; // if the proxy_member_caller returns void template class proxy_member_void_caller { friend class luabind::object; public: proxy_member_void_caller(lua_State* L_, const Tuple args) : L(L_) , m_args(args) , m_called(false) { } proxy_member_void_caller(const proxy_member_void_caller& rhs) : L(rhs.L) , m_args(rhs.m_args) , m_called(rhs.m_called) { rhs.m_called = true; } ~proxy_member_void_caller() LUABIND_MAY_THROW { if (m_called) return; m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters push_args_from_tuple<1>::apply(L, m_args); if (pcall(L, boost::tuples::length::value + 1, 0)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw luabind::error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); } template void operator[](const Policies& p) { m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters detail::push_args_from_tuple<1>::apply(L, m_args, p); if (pcall(L, boost::tuples::length::value + 1, 0)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); } private: lua_State* L; Tuple m_args; mutable bool m_called; }; } // detail #define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LUABIND_MAX_ARITY, , 1)) #include BOOST_PP_ITERATE() } #endif // LUABIND_CALL_MEMBER_HPP_INCLUDED #else #if BOOST_PP_ITERATION_FLAGS() == 1 #define LUABIND_TUPLE_PARAMS(z, n, data) const A##n * #define LUABIND_OPERATOR_PARAMS(z, n, data) const A##n & a##n template typename boost::mpl::if_ , luabind::detail::proxy_member_void_caller > , luabind::detail::proxy_member_caller > >::type call_member(object const& obj, const char* name BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _)) { typedef boost::tuples::tuple tuple_t; #if BOOST_PP_ITERATION() == 0 tuple_t args; #else tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a)); #endif typedef typename boost::mpl::if_ , luabind::detail::proxy_member_void_caller > , luabind::detail::proxy_member_caller > >::type proxy_type; // this will be cleaned up by the proxy object // once the call has been made // get the function obj.push(obj.interpreter()); lua_pushstring(obj.interpreter(), name); lua_gettable(obj.interpreter(), -2); // duplicate the self-object lua_pushvalue(obj.interpreter(), -2); // remove the bottom self-object lua_remove(obj.interpreter(), -3); // now the function and self objects // are on the stack. These will both // be popped by pcall return proxy_type(obj.interpreter(), args); } #undef LUABIND_OPERATOR_PARAMS #undef LUABIND_TUPLE_PARAMS #endif #endif luabind-1.1.1/luabind/detail/call_operator_iterate.hpp000066400000000000000000000042221366245310300230670ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #define N BOOST_PP_ITERATION() #define LUABIND_UNWRAP_PARAMETER(z, n, _) \ typename detail::unwrap_parameter_type::type \ BOOST_PP_CAT(_, n) template struct BOOST_PP_CAT(call_operator, N) : detail::operator_< BOOST_PP_CAT(call_operator, N)< Self BOOST_PP_ENUM_TRAILING_PARAMS(N, A) > > { BOOST_PP_CAT(call_operator, N)(int) {} template struct apply { static void execute( lua_State* L , typename detail::unwrap_parameter_type::type self BOOST_PP_ENUM_TRAILING(N, LUABIND_UNWRAP_PARAMETER, _) ) { using namespace detail; operator_result( L , (self(BOOST_PP_ENUM_PARAMS(N, _)), detail::operator_void_return()) , (Policies*)0 ); } }; static char const* name() { return "__call"; } }; #undef LUABIND_UNWRAP_PARAMETER #undef N luabind-1.1.1/luabind/detail/class_registry.hpp000066400000000000000000000055741366245310300215740ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_CLASS_REGISTRY_HPP_INCLUDED #define LUABIND_CLASS_REGISTRY_HPP_INCLUDED #include #include #include #include namespace luabind { namespace detail { class class_rep; extern char classes_tag; // Not used in headers, thus no LUABIND_API. struct LUABIND_API class_registry { class_registry(lua_State* L); static class_registry* get_registry(lua_State* L); int cpp_instance() const { return m_instance_metatable; } int cpp_class() const { return m_cpp_class_metatable; } int lua_instance() const { return m_instance_metatable; } int lua_class() const { return m_lua_class_metatable; } int lua_function() const { return m_lua_function_metatable; } void add_class(type_id const& info, class_rep* crep); class_rep* find_class(type_id const& info) const; std::map const& get_classes() const { return m_classes; } private: std::map m_classes; // this is a lua reference that points to the lua table // that is to be used as meta table for all C++ class // instances. It is a kind of v-table. int m_instance_metatable; // this is a lua reference to the metatable to be used // for all classes defined in C++. int m_cpp_class_metatable; // this is a lua reference to the metatable to be used // for all classes defined in lua int m_lua_class_metatable; // this metatable only contains a destructor // for luabind::Detail::free_functions::function_rep int m_lua_function_metatable; }; }} #endif // LUABIND_CLASS_REGISTRY_HPP_INCLUDED luabind-1.1.1/luabind/detail/class_rep.hpp000066400000000000000000000141331366245310300205010ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_CLASS_REP_HPP_INCLUDED #define LUABIND_CLASS_REP_HPP_INCLUDED #include #include #include #include #include #include #include namespace luabind { namespace detail { struct class_registration; // This function is used as a tag to identify "properties". LUABIND_API int property_tag(lua_State*); extern char classrep_tag; // Not used in headers, thus no LUABIND_API. // this is class-specific information, poor man's vtable // this is allocated statically (removed by the compiler) // a pointer to this structure is stored in the lua tables' // metatable with the name __classrep // it is used when matching parameters to function calls // to determine possible implicit casts // it is also used when finding the best match for overloaded // methods class cast_graph; class class_id_map; class LUABIND_API class_rep { friend struct class_registration; friend int super_callback(lua_State*); public: enum class_type { cpp_class = 0, lua_class = 1 }; // EXPECTS THE TOP VALUE ON THE LUA STACK TO // BE THE USER DATA WHERE THIS CLASS IS BEING // INSTANTIATED! class_rep(type_id const& type , const char* name , lua_State* L ); // used when creating a lua class // EXPECTS THE TOP VALUE ON THE LUA STACK TO // BE THE USER DATA WHERE THIS CLASS IS BEING // INSTANTIATED! class_rep(lua_State* L, const char* name); ~class_rep(); std::pair allocate(lua_State* L) const; // this is called as metamethod __call on the class_rep. static int constructor_dispatcher(lua_State* L); void add_base_class(class_rep* bcrep); const std::vector& bases() const LUABIND_NOEXCEPT { return m_bases; } void set_type(type_id const& t) { m_type = t; } type_id const& type() const LUABIND_NOEXCEPT { return m_type; } const char* name() const LUABIND_NOEXCEPT { return m_name; } // the lua reference to the metatable for this class' instances int metatable_ref() const LUABIND_NOEXCEPT { return m_instance_metatable; } void get_table(lua_State* L) const { m_table.push(L); } void get_default_table(lua_State* L) const { m_default_table.push(L); } class_type get_class_type() const { return m_class_type; } void add_static_constant(const char* name, int val); static int super_callback(lua_State* L); static int lua_settable_dispatcher(lua_State* L); // called from the metamethod for __index // obj is the object pointer static int static_class_gettable(lua_State* L); static int tostring(lua_State* L); // for __tostring cast_graph const& casts() const { return *m_casts; } class_id_map const& classes() const { return *m_classes; } private: // Code common to both constructors void shared_init(lua_State * L); // this is a pointer to the type_info structure for // this type // warning: this may be a problem when using dll:s, since // typeid() may actually return different pointers for the same // type. type_id m_type; // a list of info for every class this class derives from // the information stored here is sufficient to do // type casts to the base classes std::vector m_bases; // the class' name (as given when registered to lua with class_) const char* m_name; // a reference to this structure itself. Since this struct // is kept inside lua (to let lua collect it when lua_close() // is called) we need to lock it to prevent collection. // the actual reference is not currently used. handle m_self_ref; // this should always be used when accessing // members in instances of a class. // this table contains c closures for all // member functions in this class, they // may point to both static and virtual functions handle m_table; // this table contains default implementations of the // virtual functions in m_table. handle m_default_table; // the type of this class.. determines if it's written in c++ or lua class_type m_class_type; // this is a lua reference that points to the lua table // that is to be used as meta table for all instances // of this class. int m_instance_metatable; std::map m_static_constants; cast_graph* m_casts; class_id_map* m_classes; }; bool is_class_rep(lua_State* L, int index); }} //#include #endif // LUABIND_CLASS_REP_HPP_INCLUDED luabind-1.1.1/luabind/detail/constructor.hpp000066400000000000000000000071531366245310300211170ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !BOOST_PP_IS_ITERATING # ifndef LUABIND_DETAIL_CONSTRUCTOR_081018_HPP # define LUABIND_DETAIL_CONSTRUCTOR_081018_HPP # include # include # include # include # include # include # include # include namespace luabind { namespace detail { inline void inject_backref(lua_State*, void*, void*) {} template void inject_backref(lua_State* L, T* p, wrap_base*) { weak_ref(get_main_thread(L), L, 1).swap(wrap_access::ref(*p)); } template struct construct_aux; template struct construct : construct_aux::value - 2, T, Pointer, Signature> {}; template struct construct_aux<0, T, Pointer, Signature> { typedef pointer_holder holder_type; void operator()(argument const& self_) const { object_rep* self = touserdata(self_); #ifdef LUABIND_USE_CXX11 std::unique_ptr instance(new T); #else std::auto_ptr instance(new T); #endif inject_backref(self_.interpreter(), instance.get(), instance.get()); void* naked_ptr = instance.get(); Pointer ptr(instance.release()); void* storage = self->allocate(sizeof(holder_type)); self->set_instance(new (storage) holder_type( #ifdef LUABIND_USE_CXX11 std::move(ptr), registered_class::id, naked_ptr)); #else ptr, registered_class::id, naked_ptr)); #endif } }; # define BOOST_PP_ITERATION_PARAMS_1 \ (3, (1, LUABIND_MAX_ARITY, )) # include BOOST_PP_ITERATE() }} // namespace luabind::detail # endif // LUABIND_DETAIL_CONSTRUCTOR_081018_HPP #else // !BOOST_PP_IS_ITERATING # define N BOOST_PP_ITERATION() template struct construct_aux { typedef typename mpl::begin::type first; typedef typename mpl::next::type iter0; # define BOOST_PP_LOCAL_MACRO(n) \ typedef typename mpl::next< \ BOOST_PP_CAT(iter,BOOST_PP_DEC(n))>::type BOOST_PP_CAT(iter,n); \ typedef typename BOOST_PP_CAT(iter,n)::type BOOST_PP_CAT(a,BOOST_PP_DEC(n)); # define BOOST_PP_LOCAL_LIMITS (1,N) # include BOOST_PP_LOCAL_ITERATE() typedef pointer_holder holder_type; void operator()(argument const& self_, BOOST_PP_ENUM_BINARY_PARAMS(N,a,_)) const { object_rep* self = touserdata(self_); #ifdef LUABIND_USE_CXX11 std::unique_ptr instance(new T(BOOST_PP_ENUM_PARAMS(N,_))); #else std::auto_ptr instance(new T(BOOST_PP_ENUM_PARAMS(N,_))); #endif inject_backref(self_.interpreter(), instance.get(), instance.get()); void* naked_ptr = instance.get(); Pointer ptr(instance.release()); void* storage = self->allocate(sizeof(holder_type)); self->set_instance(new (storage) holder_type( #ifdef LUABIND_USE_CXX11 std::move(ptr), registered_class::id, naked_ptr)); #else ptr, registered_class::id, naked_ptr)); #endif } }; # undef N #endif luabind-1.1.1/luabind/detail/convert_to_lua.hpp000066400000000000000000000055541366245310300215600ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_CONVERT_TO_LUA_HPP_INCLUDED #define LUABIND_CONVERT_TO_LUA_HPP_INCLUDED #include #include #include #include namespace luabind { namespace detail { template struct unwrap_ref { template static const T& get(const T& r) { return r; } template struct apply { typedef T type; }; }; template<> struct unwrap_ref { template static T& get(const boost::reference_wrapper& r) { return r.get(); } template struct apply { typedef typename T::type& type; }; }; namespace mpl = boost::mpl; template void convert_to_lua(lua_State* L, const T& v) { typedef typename mpl::apply_wrap1< unwrap_ref::value> , T >::type value_type; typename mpl::apply_wrap2::type converter; converter.apply(L, unwrap_ref::value>::get(v)); } template void convert_to_lua_p(lua_State* L, const T& v, const Policies&) { typedef typename mpl::apply_wrap1< unwrap_ref::value> , T >::type value_type; typedef typename find_conversion_policy::type converter_policy; typename mpl::apply_wrap2::type converter; converter.apply(L, unwrap_ref::value>::get(v)); } }} #endif luabind-1.1.1/luabind/detail/debug.hpp000066400000000000000000000043411366245310300176140ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_DEBUG_HPP_INCLUDED #define LUABIND_DEBUG_HPP_INCLUDED #include #include #include namespace luabind { namespace detail { // prints the types of the values on the stack, in the // range [start_index, lua_gettop()] LUABIND_API std::string stack_content_by_name(lua_State* L, int start_index); }} #ifndef NDEBUG #include #include namespace luabind { namespace detail { struct stack_checker_type { stack_checker_type(lua_State* L) : m_L(L) , m_stack(lua_gettop(m_L)) {} ~stack_checker_type() { assert(m_stack == lua_gettop(m_L)); } lua_State* m_L; int m_stack; }; }} #define LUABIND_CHECK_STACK(L) BOOST_PP_CAT( \ luabind::detail::stack_checker_type stack_checker_object, __LINE__)(L) #else // (void)0,0: avoid warning about conditional expression being constant and comma operator // without side effect. #define LUABIND_CHECK_STACK(L) do {} while ((void)0,0) #endif #endif // LUABIND_DEBUG_HPP_INCLUDED luabind-1.1.1/luabind/detail/decorate_type.hpp000066400000000000000000000147001366245310300213550ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_DECORATE_TYPE_HPP_INCLUDED #define LUABIND_DECORATE_TYPE_HPP_INCLUDED #include #include namespace luabind { namespace detail { #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION template struct decorated_type { static by_value t; static inline by_value& get() { return /*by_value()*/t; } }; template by_value decorated_type::t; template struct decorated_type { static by_pointer t; static inline by_pointer& get() { return /*by_pointer()*/t; } }; template by_pointer decorated_type::t; template struct decorated_type { static by_const_pointer t; static inline by_const_pointer get() { return /*by_const_pointer()*/t; } }; template by_const_pointer decorated_type::t; template struct decorated_type { static by_const_pointer t; static inline by_const_pointer& get() { return /*by_const_pointer()*/t; } }; template by_const_pointer decorated_type::t; template struct decorated_type { static by_reference t; static inline by_reference& get() { return /*by_reference()*/t; } }; template by_reference decorated_type::t; template struct decorated_type { static by_const_reference t; static inline by_const_reference& get() { return /*by_const_reference()*/t; } }; template by_const_reference decorated_type::t; #ifndef LUABIND_NO_RVALUE_REFERENCES template struct decorated_type { static by_value t; static inline by_value& get() { return /*by_value()*/t; } }; template by_value decorated_type::t; #endif #define LUABIND_DECORATE_TYPE(t) luabind::detail::decorated_type::get() #else #include namespace { LUABIND_ANONYMOUS_FIX char decorated_type_array[64]; } template struct decorated_type_cref_impl { static void(*data())(T) { return (void(*)(T))0; } template static by_const_reference get(void(*f)(const U&)) { return by_const_reference(); } }; template struct decorated_type_ref_impl { static void(*data())(T) { return (void(*)(T))0; } template static by_reference get(void(*)(U&)) { return by_reference(); } }; template struct decorated_type_cptr_impl { template static by_const_pointer get(const U*) { return by_const_pointer(); } static T& data() { return reinterpret_cast(decorated_type_array); } }; template struct decorated_type_ptr_impl { template static by_pointer get(U*) { return by_pointer(); } static T& data() { return reinterpret_cast(decorated_type_array); } }; template struct decorated_type_value_impl { static void(*data())(T&) { return (void(*)(T&))0; } template static by_value get(void(*)(U&)) { return by_value(); } }; template<> struct decorated_type_value_impl { static by_value get(int) { return by_value(); } static int data() { return 0; } }; template struct decorated_type_array_impl { template static by_pointer get(U*) { return by_pointer(); } template static by_pointer get(void(*)(U)) { return by_pointer(); } static T& data() { return reinterpret_cast(decorated_type_array); } }; template struct decorated_type // : boost::mpl::if_ // , decorated_type_array_impl : boost::mpl::if_ , decorated_type_cref_impl , typename boost::mpl::if_ , decorated_type_ref_impl , typename boost::mpl::if_ , decorated_type_ptr_impl , typename boost::mpl::if_ , decorated_type_cptr_impl , decorated_type_value_impl >::type >::type >::type >::type // >::type { }; // #define LUABIND_DECORATE_TYPE(t) luabind::detail::decorated_type::get((void(*)(type))0) #define LUABIND_DECORATE_TYPE(t) luabind::detail::decorated_type::get(luabind::detail::decorated_type::data()) //#define LUABIND_DECORATE_TYPE(t) luabind::detail::decorated_type::get(type()) #endif }} #endif // LUABIND_DECORATE_TYPE_HPP_INCLUDED luabind-1.1.1/luabind/detail/deduce_signature.hpp000066400000000000000000000037401366245310300220420ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # ifndef LUABIND_DEDUCE_SIGNATURE_080911_HPP # define LUABIND_DEDUCE_SIGNATURE_080911_HPP # include # include # include # include # include # include namespace luabind { namespace detail { namespace mpl = boost::mpl; namespace fty = boost::function_types; template struct signature_aux { typedef F type; }; // Handle boost::function and std::function: template class F, class S> struct signature_aux< F, typename mpl::apply< // Enable only if F::result_type exists. mpl::always, typename F::result_type>::type > { typedef S type; }; template struct signature_aux: signature_aux {}; template struct is_function: fty::is_callable_builtin::type> {}; template typename boost::enable_if< is_function, fty::components::type> >::type deduce_signature(F const&, ...) { return fty::components::type>(); } template typename boost::enable_if< fty::is_member_function_pointer::type>, fty::components< typename signature_aux::type, boost::add_reference > > >::type deduce_signature(F, Wrapped*) { return fty::components< typename signature_aux::type, boost::add_reference > >(); } } } // namespace luabind::detail #endif // LUABIND_DEDUCE_SIGNATURE_080911_HPP luabind-1.1.1/luabind/detail/enum_maker.hpp000066400000000000000000000067261366245310300206620ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_ENUM_MAKER_HPP_INCLUDED #define LUABIND_ENUM_MAKER_HPP_INCLUDED #include #include #include #include namespace luabind { struct value; struct value_vector : public std::vector { // a bug in intel's compiler forces us to declare these constructors explicitly. value_vector(); virtual ~value_vector(); value_vector(const value_vector& v); value_vector& operator,(const value& rhs); }; struct value { friend class std::vector; template value(const char* name, T v) : name_(name) , val_(static_cast(v)) { assert(static_cast(val_) == v); } const char* name_; int val_; value_vector operator,(const value& rhs) const { value_vector v; v.push_back(*this); v.push_back(rhs); return v; } private: value() {} }; inline value_vector::value_vector() : std::vector() { } inline value_vector::~value_vector() {} inline value_vector::value_vector(const value_vector& rhs) : std::vector(rhs) { } inline value_vector& value_vector::operator,(const value& rhs) { push_back(rhs); return *this; } namespace detail { template struct enum_maker { explicit enum_maker(From& from): from_(from) {} enum_maker(enum_maker const& rhs): from_(rhs.from_) {} From& operator[](const value& val) { from_.add_static_constant(val.name_, val.val_); return from_; } From& operator[](const value_vector& values) { for (value_vector::const_iterator i = values.begin(); i != values.end(); ++i) { from_.add_static_constant(i->name_, i->val_); } return from_; } From& from_; private: void operator=(enum_maker const&); // C4512, assignment operator could not be generated template void operator,(T const&) const; }; } } #endif // LUABIND_ENUM_MAKER_HPP_INCLUDED luabind-1.1.1/luabind/detail/format_signature.hpp000066400000000000000000000070311366245310300220760ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_FORMAT_SIGNATURE_081014_HPP # define LUABIND_FORMAT_SIGNATURE_081014_HPP # include # include # include # include # include # include # include namespace luabind { namespace detail { namespace mpl = boost::mpl; LUABIND_API std::string get_class_name(lua_State* L, type_id const& i); template struct type_to_string { static void get(lua_State* L) { std::string const class_name = get_class_name(L, typeid(T)); lua_pushlstring(L, class_name.c_str(), class_name.size()); } }; template struct type_to_string { static void get(lua_State* L) { type_to_string::get(L); lua_pushliteral(L, "*"); lua_concat(L, 2); } }; template struct type_to_string { static void get(lua_State* L) { type_to_string::get(L); lua_pushliteral(L, "&"); lua_concat(L, 2); } }; template struct type_to_string { static void get(lua_State* L) { type_to_string::get(L); lua_pushliteral(L, " const"); lua_concat(L, 2); } }; # define LUABIND_TYPE_TO_STRING(x) \ template <> \ struct type_to_string \ { \ static void get(lua_State* L) \ { \ lua_pushliteral(L, #x); \ } \ }; # define LUABIND_INTEGRAL_TYPE_TO_STRING(x) \ LUABIND_TYPE_TO_STRING(x) \ LUABIND_TYPE_TO_STRING(unsigned x) LUABIND_INTEGRAL_TYPE_TO_STRING(char) LUABIND_INTEGRAL_TYPE_TO_STRING(short) LUABIND_INTEGRAL_TYPE_TO_STRING(int) LUABIND_INTEGRAL_TYPE_TO_STRING(long) #ifndef BOOST_NO_LONG_LONG LUABIND_INTEGRAL_TYPE_TO_STRING(long long) #endif LUABIND_TYPE_TO_STRING(void) LUABIND_TYPE_TO_STRING(bool) LUABIND_TYPE_TO_STRING(std::string) LUABIND_TYPE_TO_STRING(lua_State) LUABIND_TYPE_TO_STRING(luabind::object) LUABIND_TYPE_TO_STRING(luabind::argument) # undef LUABIND_INTEGRAL_TYPE_TO_STRING # undef LUABIND_TYPE_TO_STRING template struct type_to_string > { static void get(lua_State* L) { lua_pushliteral(L, "table"); } }; template void format_signature_aux(lua_State*, bool, End, End) {} template void format_signature_aux(lua_State* L, bool first, Iter, End end) { if (!first) lua_pushliteral(L, ","); type_to_string::get(L); format_signature_aux(L, false, typename mpl::next::type(), end); } template void format_signature(lua_State* L, char const* function, Signature) { typedef typename mpl::begin::type first; type_to_string::get(L); lua_pushliteral(L, " "); lua_pushstring(L, function); lua_pushliteral(L, "("); format_signature_aux( L , true , typename mpl::next::type() , typename mpl::end::type() ); lua_pushliteral(L, ")"); int const signature_len = static_cast(mpl::size()); lua_concat(L, signature_len * 2 + (signature_len == 1 ? 3 /* zero-argument function: account for ')' */ : 2)); } }} // namespace luabind::detail #endif // LUABIND_FORMAT_SIGNATURE_081014_HPP luabind-1.1.1/luabind/detail/garbage_collector.hpp000066400000000000000000000035061366245310300221660ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_GARBAGE_COLLECTOR_HPP_INCLUDED #define LUABIND_GARBAGE_COLLECTOR_HPP_INCLUDED #include #include namespace luabind { namespace detail { // function that is used as __gc metafunction on several objects template inline int garbage_collector(lua_State* L) { T* obj = static_cast(lua_touserdata(L, -1)); obj->~T(); return 0; } template struct garbage_collector_s { static int apply(lua_State* L) { T* obj = static_cast(lua_touserdata(L, -1)); obj->~T(); return 0; } }; }} #endif // LUABIND_GARBAGE_COLLECTOR_HPP_INCLUDED luabind-1.1.1/luabind/detail/has_get_pointer.hpp000066400000000000000000000056201366245310300217010ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin // 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. #ifndef LUABIND_HAS_GET_POINTER_051022_HPP # define LUABIND_HAS_GET_POINTER_051022_HPP # include # include # ifndef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP # include # endif namespace luabind { namespace detail { namespace has_get_pointer_ { struct any { template any(T const&); }; struct no_overload_tag {}; typedef char (&yes)[1]; typedef char (&no)[2]; no_overload_tag operator,(no_overload_tag, int); // // On compilers with ADL, we need these generic overloads in this // namespace as well as in luabind::. Otherwise get_pointer(any) // will be found before them. // # ifndef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP template T* get_pointer(T const volatile*); template # ifdef LUABIND_USE_CXX11 T* get_pointer(std::unique_ptr const&); # else T* get_pointer(std::auto_ptr const&); # endif # endif // // On compilers that doesn't support ADL, the overload below has to // live in luabind::. // # ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP }} // namespace detail::has_get_pointer_ # endif detail::has_get_pointer_::no_overload_tag get_pointer(detail::has_get_pointer_::any); # ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP namespace detail { namespace has_get_pointer_ { # endif template yes check(T const&); no check(no_overload_tag); template struct impl { static typename boost::add_reference::type x; BOOST_STATIC_CONSTANT(bool, value = sizeof(has_get_pointer_::check( (get_pointer(x),0) )) == 1 ); typedef boost::mpl::bool_ type; }; } // namespace has_get_pointer_ template struct has_get_pointer : has_get_pointer_::impl::type {}; }} // namespace luabind::detail #endif // LUABIND_HAS_GET_POINTER_051022_HPP luabind-1.1.1/luabind/detail/inheritance.hpp000066400000000000000000000101451366245310300210160ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_INHERITANCE_090217_HPP # define LUABIND_INHERITANCE_090217_HPP # include # include # include # include # include # include # include namespace luabind { namespace detail { LUABIND_API extern char classid_map_tag; LUABIND_API extern char class_map_tag; extern char cast_graph_tag; // Not used in headers, thus no LUABIND_API. typedef void*(*cast_function)(void*); typedef std::size_t class_id; class_id const unknown_class = (std::numeric_limits::max)(); class class_rep; class LUABIND_API cast_graph { public: cast_graph(); ~cast_graph(); // `src` and `p` here describe the *most derived* object. This means that // for a polymorphic type, the pointer must be cast with // dynamic_cast before being passed in here, and `src` has to // match typeid(*p). std::pair cast( void* p, class_id src, class_id target , class_id dynamic_id, void const* dynamic_ptr) const; void insert(class_id src, class_id target, cast_function cast); private: class impl; boost::scoped_ptr m_impl; }; // Maps a type_id to a class_id. Note that this actually partitions the // id-space into two, using one half for "local" ids; ids that are used only as // keys into the conversion cache. This is needed because we need a unique key // even for types that hasn't been registered explicitly. class LUABIND_API class_id_map { public: class_id_map(); class_id get(type_id const& type) const; class_id get_local(type_id const& type); void put(class_id id, type_id const& type); private: typedef std::map map_type; map_type m_classes; class_id m_local_id; static class_id const local_id_base; }; inline class_id_map::class_id_map() : m_local_id(local_id_base) {} inline class_id class_id_map::get(type_id const& type) const { map_type::const_iterator i = m_classes.find(type); if (i == m_classes.end() || i->second >= local_id_base) return unknown_class; return i->second; } inline class_id class_id_map::get_local(type_id const& type) { std::pair result = m_classes.insert( std::make_pair(type, 0)); if (result.second) result.first->second = m_local_id++; assert(m_local_id >= local_id_base); return result.first->second; } inline void class_id_map::put(class_id id, type_id const& type) { assert(id < local_id_base); std::pair result = m_classes.insert( std::make_pair(type, 0)); assert( result.second || result.first->second == id || result.first->second >= local_id_base ); result.first->second = id; } class class_map { public: class_rep* get(class_id id) const; void put(class_id id, class_rep* cls); private: std::vector m_classes; }; inline class_rep* class_map::get(class_id id) const { if (id >= m_classes.size()) return 0; return m_classes[id]; } inline void class_map::put(class_id id, class_rep* cls) { if (id >= m_classes.size()) m_classes.resize(id + 1); m_classes[id] = cls; } template struct static_cast_ { static void* execute(void* p) { return static_cast(static_cast(p)); } }; template struct dynamic_cast_ { static void* execute(void* p) { return dynamic_cast(static_cast(p)); } }; // Thread safe class_id allocation. LUABIND_API class_id allocate_class_id(type_id const& cls); template struct registered_class { static class_id const id; }; template class_id const registered_class::id = allocate_class_id(typeid(T)); template struct registered_class : registered_class {}; }} // namespace luabind::detail #endif // LUABIND_INHERITANCE_090217_HPP luabind-1.1.1/luabind/detail/instance_holder.hpp000066400000000000000000000060441366245310300216710ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_INSTANCE_HOLDER_081024_HPP # define LUABIND_INSTANCE_HOLDER_081024_HPP # include # include # include # include # include namespace luabind { namespace detail { class instance_holder { public: instance_holder(bool is_pointee_const) : m_pointee_const(is_pointee_const) {} virtual ~instance_holder() {} virtual std::pair get( cast_graph const& casts, class_id target) const = 0; virtual void release() = 0; bool pointee_const() const { return m_pointee_const; } private: bool m_pointee_const; }; namespace mpl = boost::mpl; inline mpl::false_ check_const_pointer(void*) { return mpl::false_(); } inline mpl::true_ check_const_pointer(void const*) { return mpl::true_(); } template #ifdef LUABIND_USE_CXX11 void release_ownership(std::unique_ptr& p) #else void release_ownership(std::auto_ptr& p) #endif { p.release(); } template void release_ownership(P const&) { throw std::runtime_error( "luabind: smart pointer does not allow ownership transfer"); } template class_id static_class_id(T*) { return registered_class::id; } template class pointer_holder : public instance_holder { public: pointer_holder( P p, class_id dynamic_id, void* dynamic_ptr ) : instance_holder(check_const_pointer(false ? get_pointer(p) : 0)) #ifdef LUABIND_USE_CXX11 , m_p(std::move(p)) #else , m_p(p) #endif , m_weak(0) , m_dynamic_id(dynamic_id) , m_dynamic_ptr(dynamic_ptr) {} std::pair get(cast_graph const& casts, class_id target) const { if (target == registered_class

::id) return std::pair(&this->m_p, 0); void* naked_ptr = const_cast(static_cast( m_weak ? m_weak : get_pointer(m_p))); if (!naked_ptr) return std::pair(static_cast(0), 0); return casts.cast( naked_ptr , static_class_id(false ? get_pointer(m_p) : 0) , target , m_dynamic_id , m_dynamic_ptr ); } void release() { m_weak = const_cast(static_cast( get_pointer(m_p))); release_ownership(m_p); } private: mutable P m_p; // weak will hold a possibly stale pointer to the object owned // by p once p has released it's owership. This is a workaround // to make adopt() work with virtual function wrapper classes. void* m_weak; class_id m_dynamic_id; void* m_dynamic_ptr; }; }} // namespace luabind::detail #endif // LUABIND_INSTANCE_HOLDER_081024_HPP luabind-1.1.1/luabind/detail/link_compatibility.hpp000066400000000000000000000037121366245310300224150ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_LINK_COMPATIBILITY_HPP_INCLUDED #define LUABIND_LINK_COMPATIBILITY_HPP_INCLUDED #include namespace luabind { namespace detail { #ifdef LUABIND_NOT_THREADSAFE LUABIND_API void not_threadsafe_defined_conflict(); #else LUABIND_API void not_threadsafe_not_defined_conflict(); #endif #ifdef LUABIND_NO_ERROR_CHECKING LUABIND_API void no_error_checking_defined_conflict(); #else LUABIND_API void no_error_checking_not_defined_conflict(); #endif inline void check_link_compatibility() { #ifdef LUABIND_NOT_THREADSAFE not_threadsafe_defined_conflict(); #else not_threadsafe_not_defined_conflict(); #endif #ifdef LUABIND_NO_ERROR_CHECKING no_error_checking_defined_conflict(); #else no_error_checking_not_defined_conflict(); #endif } }} #endif luabind-1.1.1/luabind/detail/make_instance.hpp000066400000000000000000000053731366245310300213350ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_DETAIL_MAKE_INSTANCE_090310_HPP # define LUABIND_DETAIL_MAKE_INSTANCE_090310_HPP # include # include # include namespace luabind { namespace detail { template std::pair get_dynamic_class_aux( lua_State* L, T const* p, mpl::true_) { lua_rawgetp(L, LUA_REGISTRYINDEX, &classid_map_tag); class_id_map& class_ids = *static_cast( lua_touserdata(L, -1)); lua_pop(L, 1); return std::make_pair( class_ids.get_local(typeid(*p)) , dynamic_cast(const_cast(p)) ); } template std::pair get_dynamic_class_aux( lua_State*, T const* p, mpl::false_) { return std::make_pair( registered_class::id, static_cast(const_cast(p))); } template std::pair get_dynamic_class(lua_State* L, T* p) { return get_dynamic_class_aux(L, p, boost::is_polymorphic()); } template class_rep* get_pointee_class(class_map const& classes, T*) { return classes.get(registered_class::id); } template class_rep* get_pointee_class(lua_State* L, P const& p, class_id dynamic_id) { lua_rawgetp(L, LUA_REGISTRYINDEX, &class_map_tag); class_map const& classes = *static_cast( lua_touserdata(L, -1)); lua_pop(L, 1); class_rep* cls = classes.get(dynamic_id); if (!cls) cls = get_pointee_class(classes, get_pointer(p)); return cls; } // Create an appropriate instance holder for the given pointer like object. template void make_instance(lua_State* L, P p) { std::pair dynamic = get_dynamic_class(L, get_pointer(p)); class_rep* cls = get_pointee_class(L, p, dynamic.first); if (!cls) { throw std::runtime_error("Trying to use unregistered class"); } object_rep* instance = push_new_instance(L, cls); typedef pointer_holder

holder_type; void* storage = instance->allocate(sizeof(holder_type)); try { #ifdef LUABIND_USE_CXX11 new (storage) holder_type(std::move(p), dynamic.first, dynamic.second); #else new (storage) holder_type(p, dynamic.first, dynamic.second); #endif } catch (...) { instance->deallocate(storage); lua_pop(L, 1); throw; } instance->set_instance(static_cast(storage)); } }} // namespace luabind::detail #endif // LUABIND_DETAIL_MAKE_INSTANCE_090310_HPP luabind-1.1.1/luabind/detail/most_derived.hpp000066400000000000000000000031021366245310300212040ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin and Arvid Norberg // 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. #ifndef MOST_DERIVED_051018_HPP # define MOST_DERIVED_051018_HPP # include # include namespace luabind { namespace detail { template struct most_derived { typedef typename boost::mpl::if_< boost::is_base_and_derived , WrappedClass , Class >::type type; }; }} // namespace luabind::detail #endif // MOST_DERIVED_051018_HPP luabind-1.1.1/luabind/detail/object.hpp000066400000000000000000001011621366245310300177730ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_OBJECT_050419_HPP #define LUABIND_OBJECT_050419_HPP #include #include #include #include #include #include #include #include #include #include #include // iterator #include #include // value_wrapper_traits specializations #include #include #include #include namespace luabind { namespace adl { namespace mpl = boost::mpl; template class object_interface; namespace is_object_interface_aux { typedef char (&yes)[1]; typedef char (&no)[2]; template yes check(object_interface*); no check(void*); template struct impl { BOOST_STATIC_CONSTANT(bool, value = sizeof(is_object_interface_aux::check(static_cast(0))) == sizeof(yes) ); typedef mpl::bool_ type; }; } // namespace detail template struct is_object_interface : is_object_interface_aux::impl::type {}; template struct enable_binary # ifndef BOOST_NO_SFINAE : boost::enable_if< mpl::or_< is_object_interface , is_object_interface > , R > {}; # else { typedef R type; }; # endif template int binary_interpreter(lua_State*& L, T const& lhs, U const& rhs , boost::mpl::true_, boost::mpl::true_) { L = value_wrapper_traits::interpreter(lhs); lua_State* L2 = value_wrapper_traits::interpreter(rhs); // you are comparing objects with different interpreters // that's not allowed. assert(L == L2 || L == 0 || L2 == 0); // if the two objects we compare have different interpreters // then they if (L != L2) return -1; if (L == 0) return 1; return 0; } template int binary_interpreter(lua_State*& L, T const& x, U const& , boost::mpl::true_, boost::mpl::false_) { L = value_wrapper_traits::interpreter(x); return 0; } template int binary_interpreter(lua_State*& L, T const&, U const& x, boost::mpl::false_, boost::mpl::true_) { L = value_wrapper_traits::interpreter(x); return 0; } template int binary_interpreter(lua_State*& L, T const& x, U const& y) { return binary_interpreter( L , x , y , is_value_wrapper() , is_value_wrapper() ); } #define LUABIND_BINARY_OP_DEF(op, fn) \ template \ typename enable_binary::type \ operator op(LHS const& lhs, RHS const& rhs) \ { \ lua_State* L = 0; \ switch (binary_interpreter(L, lhs, rhs)) \ { \ case 1: \ return true; \ case -1: \ return false; \ } \ \ assert(L); \ \ detail::stack_pop pop1(L, 1); \ push(L, lhs); \ detail::stack_pop pop2(L, 1); \ push(L, rhs); \ \ return lua_compare(L, -1, -2, fn) != 0; \ } LUABIND_BINARY_OP_DEF(==, LUA_OPEQ) LUABIND_BINARY_OP_DEF(<, LUA_OPLT) inline int value_to_string(lua_State* L) { assert(lua_gettop(L) == 1); luaL_tolstring(L, 1, 0); return 1; } template std::ostream& operator<<(std::ostream& os , object_interface const& v) { using namespace luabind; lua_State* L = value_wrapper_traits::interpreter( static_cast(v)); detail::stack_pop pop(L, 1); lua_pushcfunction(L, &value_to_string); value_wrapper_traits::unwrap(L , static_cast(v)); if (lua_pcall(L, 1, 1, 0) != LUA_OK) { lua_pop(L, 1); // Pop error. os.setstate(std::ios::failbit); return os; } size_t len; char const* p = lua_tolstring(L, -1, &len); std::copy(p, p + len, std::ostream_iterator(os)); return os; } #undef LUABIND_BINARY_OP_DEF template typename enable_binary::type operator>(LHS const& lhs, RHS const& rhs) { return !(lhs < rhs || lhs == rhs); } template typename enable_binary::type operator<=(LHS const& lhs, RHS const& rhs) { return lhs < rhs || lhs == rhs; } template typename enable_binary::type operator>=(LHS const& lhs, RHS const& rhs) { return !(lhs < rhs); } template typename enable_binary::type operator!=(LHS const& lhs, RHS const& rhs) { return !(lhs == rhs); } template struct call_proxy; template class index_proxy; class object; template class object_interface { struct safe_bool_type {}; public: call_proxy > operator()(); template call_proxy< Derived , boost::tuples::tuple > operator()(A0 const& a0) { typedef boost::tuples::tuple arguments; return call_proxy( derived() , arguments(&a0) ); } template call_proxy< Derived , boost::tuples::tuple > operator()(A0 const& a0, A1 const& a1) { typedef boost::tuples::tuple arguments; return call_proxy( derived() , arguments(&a0, &a1) ); } // The rest of the overloads are PP-generated. #define BOOST_PP_ITERATION_PARAMS_1 (3, \ (3, LUABIND_MAX_ARITY, )) #include BOOST_PP_ITERATE() operator safe_bool_type*() const { lua_State* L = value_wrapper_traits::interpreter(derived()); if (!L) return 0; value_wrapper_traits::unwrap(L, derived()); detail::stack_pop pop(L, 1); return lua_toboolean(L, -1) == 1 ? reinterpret_cast(1) : 0; } private: Derived& derived() { return *static_cast(this); } Derived const& derived() const { return *static_cast(this); } }; #ifdef LUABIND_USE_VALUE_WRAPPER_TAG struct iterator_proxy_tag; #endif template class iterator_proxy : public object_interface > { public: #ifdef LUABIND_USE_VALUE_WRAPPER_TAG typedef iterator_proxy_tag value_wrapper_tag; #endif iterator_proxy(lua_State* L, handle const& table, handle const& key) : m_interpreter(L) , m_table_index(lua_gettop(L) + 1) , m_key_index(m_table_index + 1) { table.push(m_interpreter); key.push(m_interpreter); } iterator_proxy(iterator_proxy const& other) : m_interpreter(other.m_interpreter) , m_table_index(other.m_table_index) , m_key_index(other.m_key_index) { other.m_interpreter = 0; } ~iterator_proxy() { if (m_interpreter) lua_pop(m_interpreter, 2); } // this will set the value to nil iterator_proxy & operator=(luabind::detail::nil_type) { lua_pushvalue(m_interpreter, m_key_index); lua_pushnil(m_interpreter); AccessPolicy::set(m_interpreter, m_table_index); return *this; } template iterator_proxy& operator=(T const& value) { lua_pushvalue(m_interpreter, m_key_index); push(m_interpreter, value); AccessPolicy::set(m_interpreter, m_table_index); return *this; } template index_proxy > operator[](Key const& key) { return index_proxy >( *this, m_interpreter, key ); } // This is non-const to prevent conversion on lvalues. operator object(); lua_State* interpreter() const { return m_interpreter; } void push(lua_State* L) const { assert(L == m_interpreter); (void)L; lua_pushvalue(m_interpreter, m_key_index); AccessPolicy::get(m_interpreter, m_table_index); } private: mutable lua_State* m_interpreter; int m_table_index; int m_key_index; }; } // namespace adl namespace detail { struct basic_access { static void set(lua_State* interpreter, int table) { lua_settable(interpreter, table); } static void get(lua_State* interpreter, int table) { lua_gettable(interpreter, table); } }; struct raw_access { static void set(lua_State* interpreter, int table) { lua_rawset(interpreter, table); } static void get(lua_State* interpreter, int table) { lua_rawget(interpreter, table); } }; template class basic_iterator : public boost::iterator_facade< basic_iterator , adl::iterator_proxy , boost::single_pass_traversal_tag , adl::iterator_proxy > { public: basic_iterator() : m_interpreter(0) {} template explicit basic_iterator(ValueWrapper const& value_wrapper) : m_interpreter( value_wrapper_traits::interpreter(value_wrapper) ) { detail::stack_pop pop(m_interpreter, 1); value_wrapper_traits::unwrap(m_interpreter, value_wrapper); lua_pushnil(m_interpreter); if (lua_next(m_interpreter, -2) != 0) { detail::stack_pop pop2(m_interpreter, 2); handle(m_interpreter, -2).swap(m_key); } else { m_interpreter = 0; return; } handle(m_interpreter, -1).swap(m_table); } adl::object key() const; private: friend class boost::iterator_core_access; void increment() { m_table.push(m_interpreter); m_key.push(m_interpreter); detail::stack_pop pop(m_interpreter, 1); if (lua_next(m_interpreter, -2) != 0) { m_key.replace(m_interpreter, -2); lua_pop(m_interpreter, 2); } else { m_interpreter = 0; handle().swap(m_table); handle().swap(m_key); } } bool equal(basic_iterator const& other) const { if (m_interpreter == 0 && other.m_interpreter == 0) return true; if (m_interpreter != other.m_interpreter) return false; detail::stack_pop pop(m_interpreter, 2); m_key.push(m_interpreter); other.m_key.push(m_interpreter); return lua_compare(m_interpreter, -2, -1, LUA_OPEQ) != 0; } adl::iterator_proxy dereference() const { return adl::iterator_proxy(m_interpreter, m_table, m_key); } lua_State* m_interpreter; handle m_table; handle m_key; }; #if BOOST_VERSION < 105700 // Needed because of some strange ADL issues. #define LUABIND_OPERATOR_ADL_WKND(op) \ inline bool operator op( \ basic_iterator const& x \ , basic_iterator const& y) \ { \ return boost::operator op(x, y); \ } \ \ inline bool operator op( \ basic_iterator const& x \ , basic_iterator const& y) \ { \ return boost::operator op(x, y); \ } LUABIND_OPERATOR_ADL_WKND(==) LUABIND_OPERATOR_ADL_WKND(!=) #undef LUABIND_OPERATOR_ADL_WKND #endif // BOOST_VERSION < 105700 } // namespace detail namespace adl { #ifdef LUABIND_USE_VALUE_WRAPPER_TAG struct index_proxy_tag; #endif template class index_proxy : public object_interface > { public: #ifdef LUABIND_USE_VALUE_WRAPPER_TAG typedef index_proxy_tag value_wrapper_tag; #endif typedef index_proxy this_type; template index_proxy(Next const& next, lua_State* L, Key const& key) : m_next(next) , m_interpreter(L) , m_key_index(lua_gettop(L) + 1) { luabind::push(m_interpreter, key); } index_proxy(index_proxy const& other) : m_next(other.m_next) , m_interpreter(other.m_interpreter) , m_key_index(other.m_key_index) { other.m_interpreter = 0; } ~index_proxy() { if (m_interpreter) lua_pop(m_interpreter, 1); } // This is non-const to prevent conversion on lvalues. operator object(); // this will set the value to nil this_type& operator=(luabind::detail::nil_type) { value_wrapper_traits::unwrap(m_interpreter, m_next); detail::stack_pop pop(m_interpreter, 1); lua_pushvalue(m_interpreter, m_key_index); lua_pushnil(m_interpreter); lua_settable(m_interpreter, -3); return *this; } template this_type& operator=(T const& value) { value_wrapper_traits::unwrap(m_interpreter, m_next); detail::stack_pop pop(m_interpreter, 1); lua_pushvalue(m_interpreter, m_key_index); luabind::push(m_interpreter, value); lua_settable(m_interpreter, -3); return *this; } this_type& operator=(this_type const& value) { value_wrapper_traits::unwrap(m_interpreter, m_next); detail::stack_pop pop(m_interpreter, 1); lua_pushvalue(m_interpreter, m_key_index); luabind::push(m_interpreter, value); lua_settable(m_interpreter, -3); return *this; } template index_proxy operator[](T const& key) { return index_proxy(*this, m_interpreter, key); } void push(lua_State* L); lua_State* interpreter() const { return m_interpreter; } private: struct hidden_type {}; // this_type& operator=(index_proxy const&); Next const& m_next; mutable lua_State* m_interpreter; int m_key_index; }; } // namespace adl typedef detail::basic_iterator iterator; typedef detail::basic_iterator raw_iterator; #ifndef LUABIND_USE_VALUE_WRAPPER_TAG template struct value_wrapper_traits > #else template<> struct value_wrapper_traits #endif { typedef boost::mpl::true_ is_specialized; template static lua_State* interpreter(adl::index_proxy const& proxy) { return proxy.interpreter(); } template static void unwrap(lua_State* interpreter, adl::index_proxy const& proxy) { const_cast&>(proxy).push(interpreter); } }; #ifndef LUABIND_USE_VALUE_WRAPPER_TAG template struct value_wrapper_traits > #else template<> struct value_wrapper_traits #endif { typedef boost::mpl::true_ is_specialized; template static lua_State* interpreter(Proxy const& p) { return p.interpreter(); } template static void unwrap(lua_State* interpreter, Proxy const& p) { p.push(interpreter); } }; namespace adl { // An object holds a reference to a Lua value residing // in the registry. class object : public object_interface { public: object() {} explicit object(handle const& other) : m_handle(other) {} explicit object(from_stack const& stack_reference) : m_handle(stack_reference.interpreter, stack_reference.index) { } template object(lua_State* L, T const& value) { luabind::push(L, value); detail::stack_pop pop(L, 1); handle(L, -1).swap(m_handle); } template object(lua_State* L, T const& value, Policies const&) { luabind::push(L, value, Policies()); detail::stack_pop pop(L, 1); handle(L, -1).swap(m_handle); } void push(lua_State* L) const; lua_State* interpreter() const; bool is_valid() const; template index_proxy operator[](T const& key) const { return index_proxy( *this, m_handle.interpreter(), key ); } void swap(object& other) { m_handle.swap(other.m_handle); } private: handle m_handle; }; inline void object::push(lua_State* L) const { m_handle.push(L); } inline lua_State* object::interpreter() const { return m_handle.interpreter(); } inline bool object::is_valid() const { return m_handle.interpreter() != 0; } class argument : public object_interface { public: argument(from_stack const& stack_reference) : m_interpreter(stack_reference.interpreter) , m_index(stack_reference.index) { if (m_index < 0) m_index = lua_gettop(m_interpreter) + m_index + 1; } template index_proxy operator[](T const& key) const { return index_proxy(*this, m_interpreter, key); } void push(lua_State* L) const { lua_pushvalue(L, m_index); } lua_State* interpreter() const { return m_interpreter; } private: lua_State* m_interpreter; int m_index; }; } // namespace adl using adl::object; using adl::argument; #ifndef LUABIND_USE_VALUE_WRAPPER_TAG template struct value_wrapper_traits > #else template<> struct value_wrapper_traits #endif { typedef boost::mpl::true_ is_specialized; template static lua_State* interpreter(adl::call_proxy const& proxy) { return value_wrapper_traits::interpreter(*proxy.value_wrapper); } template static void unwrap(lua_State*, adl::call_proxy const& proxy) { object result = const_cast&>(proxy); result.push(result.interpreter()); } }; template<> struct value_wrapper_traits { typedef boost::mpl::true_ is_specialized; static lua_State* interpreter(object const& value) { return value.interpreter(); } static void unwrap(lua_State* L, object const& value) { value.push(L); } static bool check(...) { return true; } }; template<> struct value_wrapper_traits { typedef boost::mpl::true_ is_specialized; static lua_State* interpreter(argument const& value) { return value.interpreter(); } static void unwrap(lua_State* L, argument const& value) { value.push(L); } static bool check(...) { return true; } }; template inline void adl::index_proxy::push(lua_State* L) { assert(L == m_interpreter); (void)L; value_wrapper_traits::unwrap(m_interpreter, m_next); lua_pushvalue(m_interpreter, m_key_index); lua_gettable(m_interpreter, -2); lua_remove(m_interpreter, -2); } template inline adl::index_proxy::operator object() { detail::stack_pop pop(m_interpreter, 1); push(m_interpreter); return object(from_stack(m_interpreter, -1)); } template adl::iterator_proxy::operator object() { lua_pushvalue(m_interpreter, m_key_index); AccessPolicy::get(m_interpreter, m_table_index); detail::stack_pop pop(m_interpreter, 1); return object(from_stack(m_interpreter, -1)); } template object detail::basic_iterator::key() const { return object(m_key); } template T object_cast(ValueWrapper const& value_wrapper, Policies const&) { lua_State* L = value_wrapper_traits::interpreter(value_wrapper); if (!L) return detail::throw_error_policy::handle_error(L, typeid(void)); value_wrapper_traits::unwrap(L, value_wrapper); detail::stack_pop pop(L, 1); return from_lua(L, -1, Policies()); } template T object_cast(ValueWrapper const& value_wrapper) { return object_cast(value_wrapper, detail::null_type()); } template boost::optional object_cast_nothrow(ValueWrapper const& value_wrapper, Policies const&) { lua_State* L = value_wrapper_traits::interpreter(value_wrapper); if (!L) return detail::nothrow_error_policy::handle_error(L, typeid(void)); value_wrapper_traits::unwrap(L, value_wrapper); detail::stack_pop pop(L, 1); return from_lua_nothrow(L, -1, Policies()); } template boost::optional object_cast_nothrow(ValueWrapper const& value_wrapper) { return object_cast_nothrow(value_wrapper, detail::null_type()); } namespace detail { template struct push_args_from_tuple { template inline static void apply(lua_State* L, const boost::tuples::cons& x, const Policies& p) { convert_to_lua_p(L, *x.get_head(), p); push_args_from_tuple::apply(L, x.get_tail(), p); } template inline static void apply(lua_State* L, const boost::tuples::cons& x) { convert_to_lua(L, *x.get_head()); push_args_from_tuple::apply(L, x.get_tail()); } template inline static void apply(lua_State*, const boost::tuples::null_type&, const Policies&) {} inline static void apply(lua_State*, const boost::tuples::null_type&) {} }; } // namespace detail namespace adl { template struct call_proxy { call_proxy(ValueWrapper& wrapper, Arguments args) : value_wrapper(&wrapper) , arguments(args) {} call_proxy(call_proxy const& other) : value_wrapper(other.value_wrapper) , arguments(other.arguments) { other.value_wrapper = 0; } ~call_proxy() LUABIND_MAY_THROW { if (value_wrapper) call(static_cast(0)); } operator object() { return call(static_cast(0)); } template object operator[](Policies const&) { return call(static_cast(0)); } template object call(Policies*) { lua_State* interpreter = value_wrapper_traits::interpreter( *value_wrapper ); value_wrapper_traits::unwrap( interpreter , *value_wrapper ); value_wrapper = 0; detail::push_args_from_tuple<1>::apply(interpreter, arguments, Policies()); if (detail::pcall(interpreter, boost::tuples::length::value, 1)) { #ifndef LUABIND_NO_EXCEPTIONS throw luabind::error(interpreter); #else error_callback_fun e = get_error_callback(); if (e) e(interpreter); assert(0 && "the lua function threw an error and exceptions are disabled." "if you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } detail::stack_pop pop(interpreter, 1); return object(from_stack(interpreter, -1)); } mutable ValueWrapper* value_wrapper; Arguments arguments; }; template call_proxy > object_interface::operator()() { return call_proxy >( derived() , boost::tuples::tuple<>() ); } // Simple value_wrapper adaptor with the sole purpose of helping with // overload resolution. Use this as a function parameter type instead // of "object" or "argument" to restrict the parameter to Lua tables. template struct table : Base { table(from_stack const& stack_reference) : Base(stack_reference) {} }; } // namespace adl using adl::table; template struct value_wrapper_traits > : value_wrapper_traits { static bool check(lua_State* L, int idx) { return value_wrapper_traits::check(L, idx) && lua_istable(L, idx); } }; inline object newtable(lua_State* interpreter) { lua_newtable(interpreter); detail::stack_pop pop(interpreter, 1); return object(from_stack(interpreter, -1)); } // this could be optimized by returning a proxy inline object globals(lua_State* interpreter) { lua_pushglobaltable(interpreter); detail::stack_pop pop(interpreter, 1); return object(from_stack(interpreter, -1)); } // this could be optimized by returning a proxy inline object registry(lua_State* interpreter) { lua_pushvalue(interpreter, LUA_REGISTRYINDEX); detail::stack_pop pop(interpreter, 1); return object(from_stack(interpreter, -1)); } template inline object gettable(ValueWrapper const& table, K const& key) { lua_State* interpreter = value_wrapper_traits::interpreter( table ); value_wrapper_traits::unwrap(interpreter, table); detail::stack_pop pop(interpreter, 2); push(interpreter, key); lua_gettable(interpreter, -2); return object(from_stack(interpreter, -1)); } template inline void settable(ValueWrapper const& table, K const& key, T const& value) { lua_State* interpreter = value_wrapper_traits::interpreter( table ); // TODO: Exception safe? value_wrapper_traits::unwrap(interpreter, table); detail::stack_pop pop(interpreter, 1); push(interpreter, key); push(interpreter, value); lua_settable(interpreter, -3); } template inline object rawget(ValueWrapper const& table, K const& key) { lua_State* interpreter = value_wrapper_traits::interpreter( table ); value_wrapper_traits::unwrap(interpreter, table); detail::stack_pop pop(interpreter, 2); push(interpreter, key); lua_rawget(interpreter, -2); return object(from_stack(interpreter, -1)); } template inline void rawset(ValueWrapper const& table, K const& key, T const& value) { lua_State* interpreter = value_wrapper_traits::interpreter( table ); // TODO: Exception safe? value_wrapper_traits::unwrap(interpreter, table); detail::stack_pop pop(interpreter, 1); push(interpreter, key); push(interpreter, value); lua_rawset(interpreter, -3); } template inline int type(ValueWrapper const& value) { lua_State* interpreter = value_wrapper_traits::interpreter( value ); value_wrapper_traits::unwrap(interpreter, value); detail::stack_pop pop(interpreter, 1); return lua_type(interpreter, -1); } template inline object getmetatable(ValueWrapper const& obj) { lua_State* interpreter = value_wrapper_traits::interpreter( obj ); value_wrapper_traits::unwrap(interpreter, obj); detail::stack_pop pop(interpreter, 2); lua_getmetatable(interpreter, -1); return object(from_stack(interpreter, -1)); } template inline void setmetatable( ValueWrapper1 const& obj, ValueWrapper2 const& metatable) { lua_State* interpreter = value_wrapper_traits::interpreter( obj ); value_wrapper_traits::unwrap(interpreter, obj); detail::stack_pop pop(interpreter, 1); value_wrapper_traits::unwrap(interpreter, metatable); lua_setmetatable(interpreter, -2); } template inline lua_CFunction tocfunction(ValueWrapper const& value) { lua_State* interpreter = value_wrapper_traits::interpreter( value ); value_wrapper_traits::unwrap(interpreter, value); detail::stack_pop pop(interpreter, 1); return lua_tocfunction(interpreter, -1); } template inline T* touserdata(ValueWrapper const& value) { lua_State* interpreter = value_wrapper_traits::interpreter( value ); value_wrapper_traits::unwrap(interpreter, value); detail::stack_pop pop(interpreter, 1); return static_cast(lua_touserdata(interpreter, -1)); } template inline object getupvalue(ValueWrapper const& value, int index) { lua_State* interpreter = value_wrapper_traits::interpreter( value ); value_wrapper_traits::unwrap(interpreter, value); detail::stack_pop pop(interpreter, 2); lua_getupvalue(interpreter, -1, index); return object(from_stack(interpreter, -1)); } template inline void setupvalue( ValueWrapper1 const& function, int index, ValueWrapper2 const& value) { lua_State* interpreter = value_wrapper_traits::interpreter( function ); value_wrapper_traits::unwrap(interpreter, function); detail::stack_pop pop(interpreter, 1); value_wrapper_traits::unwrap(interpreter, value); lua_setupvalue(interpreter, -2, index); } template object property(GetValueWrapper const& get) { lua_State* interpreter = value_wrapper_traits::interpreter( get ); value_wrapper_traits::unwrap(interpreter, get); lua_pushnil(interpreter); lua_pushcclosure(interpreter, &detail::property_tag, 2); detail::stack_pop pop(interpreter, 1); return object(from_stack(interpreter, -1)); } template object property(GetValueWrapper const& get, SetValueWrapper const& set) { lua_State* interpreter = value_wrapper_traits::interpreter( get ); value_wrapper_traits::unwrap(interpreter, get); value_wrapper_traits::unwrap(interpreter, set); lua_pushcclosure(interpreter, &detail::property_tag, 2); detail::stack_pop pop(interpreter, 1); return object(from_stack(interpreter, -1)); } } // namespace luabind #endif // LUABIND_OBJECT_050419_HPP luabind-1.1.1/luabind/detail/object_call.hpp000066400000000000000000000035531366245310300207730ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin and Arvid Norberg // 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. #if !BOOST_PP_IS_ITERATING # error Do not include object_call.hpp directly! #endif #include #include #include #define N BOOST_PP_ITERATION() template call_proxy< Derived , boost::tuples::tuple< BOOST_PP_ENUM_BINARY_PARAMS(N, A, const* BOOST_PP_INTERCEPT) > > operator()(BOOST_PP_ENUM_BINARY_PARAMS(N, A, const& a)) { typedef boost::tuples::tuple< BOOST_PP_ENUM_BINARY_PARAMS(N, A, const* BOOST_PP_INTERCEPT) > arguments; return call_proxy( derived() , arguments(BOOST_PP_ENUM_PARAMS(N, &a)) ); } #undef N luabind-1.1.1/luabind/detail/object_rep.hpp000066400000000000000000000105671366245310300206510ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_OBJECT_REP_HPP_INCLUDED #define LUABIND_OBJECT_REP_HPP_INCLUDED #include #include #include #include namespace luabind { namespace detail { // implements the selection between dynamic dispatch // or default implementation calls from within a virtual // function wrapper. The input is the self reference on // the top of the stack. Output is the function to call // on the top of the stack (the input self reference will // be popped) LUABIND_API void do_call_member_selection(lua_State* L, char const* name); void finalize(lua_State* L, class_rep* crep); // this class is allocated inside lua for each pointer. // it contains the actual c++ object-pointer. // it also tells if it is const or not. class LUABIND_API object_rep { public: object_rep(instance_holder* instance, class_rep* crep); ~object_rep(); const class_rep* crep() const { return m_classrep; } class_rep* crep() { return m_classrep; } void set_instance(instance_holder* instance) { m_instance = instance; } void add_dependency(lua_State* L, int index); void release_dependency_refs(lua_State* L); std::pair get_instance(class_id target) const { if (m_instance == 0) return std::pair(static_cast(0), -1); return m_instance->get(m_classrep->casts(), target); } bool is_const() const { return m_instance && m_instance->pointee_const(); } void release() { if (m_instance) m_instance->release(); } void* allocate(std::size_t size) { if (size <= instance_buffer_size) return &m_instance_buffer; return std::malloc(size); } void deallocate(void* storage) { if (storage == &m_instance_buffer) return; std::free(storage); } private: object_rep(object_rep const&); void operator=(object_rep const&); BOOST_STATIC_CONSTANT(std::size_t, instance_buffer_size=32); boost::aligned_storage m_instance_buffer; instance_holder* m_instance; class_rep* m_classrep; // the class information about this object's type std::size_t m_dependency_cnt; // counts dependencies }; template struct delete_s { static void apply(void* ptr) { delete static_cast(ptr); } }; template struct destruct_only_s { static void apply(void* ptr) { // Removes unreferenced formal parameter warning on VC7. (void)ptr; #ifndef NDEBUG int completeness_check[sizeof(T)]; (void)completeness_check; #endif static_cast(ptr)->~T(); } }; LUABIND_API object_rep* get_instance(lua_State* L, int index); LUABIND_API void push_instance_metatable(lua_State* L); LUABIND_API object_rep* push_new_instance(lua_State* L, class_rep* cls); }} #endif // LUABIND_OBJECT_REP_HPP_INCLUDED luabind-1.1.1/luabind/detail/operator_id.hpp000066400000000000000000000046411366245310300210400ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_OPERATOR_ID_HPP_INCLUDED #define LUABIND_OPERATOR_ID_HPP_INCLUDED #include namespace luabind { namespace detail { enum operator_id { op_add = 0, op_sub, op_mul, op_div, op_mod, op_pow, op_lt, op_le, op_eq, op_call, op_unm, op_tostring, op_concat, op_len, number_of_operators }; inline const char* get_operator_name(int i) { static const char* a[number_of_operators] = { "__add", "__sub", "__mul", "__div", "__mod", "__pow", "__lt", "__le", "__eq", "__call", "__unm", "__tostring", "__concat", "__len" }; return a[i]; } inline const char* get_operator_symbol(int i) { static const char* a[number_of_operators] = { "+", "-", "*", "/", "%", "^", "<", "<=", "==", "()", "- (unary)", "tostring", "..", "#" }; return a[i]; } inline bool is_unary(int i) { // the reason why unary minus is not considered a unary operator here is // that it always is given two parameters, where the second parameter always // is nil. return i == op_tostring; } }} #endif // LUABIND_OPERATOR_ID_HPP_INCLUDED luabind-1.1.1/luabind/detail/other.hpp000066400000000000000000000063321366245310300176510ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_OTHER_HPP_INCLUDED #define LUABIND_OTHER_HPP_INCLUDED // header derived from source code found in Boost.Python // Copyright David Abrahams 2002. Permission to copy, use, // modify, sell and distribute this software is granted provided this // copyright notice appears in all copies. This software is provided // "as is" without express or implied warranty, and with no claim as // to its suitability for any purpose. #include #include namespace luabind { template struct other { typedef T type; }; } #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION namespace luabind { namespace detail { template class unwrap_other { public: typedef T type; }; template class unwrap_other > { public: typedef T type; }; }} // namespace luabind::detail # else // no partial specialization #include namespace luabind { namespace detail { typedef char (&yes_other_t)[1]; typedef char (&no_other_t)[2]; no_other_t is_other_test(...); template yes_other_t is_other_test(type_< other >); template struct other_unwrapper { template struct apply { typedef T type; }; }; template<> struct other_unwrapper { template struct apply { typedef typename T::type type; }; }; template class is_other { public: BOOST_STATIC_CONSTANT( bool, value = ( sizeof(detail::is_other_test(type_())) == sizeof(detail::yes_other_t))); }; template class unwrap_other : public detail::other_unwrapper< is_other::value >::template apply {}; }} // namespace luabind::detail #endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION #endif // LUABIND_OTHER_HPP_INCLUDED luabind-1.1.1/luabind/detail/pcall.hpp000066400000000000000000000026621366245310300176250ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_PCALL_HPP_INCLUDED #define LUABIND_PCALL_HPP_INCLUDED #include #include namespace luabind { namespace detail { LUABIND_API int pcall(lua_State *L, int nargs, int nresults); LUABIND_API int resume_impl(lua_State *L, int nargs, int nresults); }} #endif luabind-1.1.1/luabind/detail/pointee_sizeof.hpp000066400000000000000000000034601366245310300215510ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #ifndef POINTEE_SIZEOF_040211_HPP #define POINTEE_SIZEOF_040211_HPP #include namespace luabind { namespace detail { template T& deref_type(T(*)(), int); template T& deref_type(T*(*)(), long); } // namespace detail // returns the indirect sizeof U, as in // sizeof(T*) = sizeof(T) // sizeof(T&) = sizeof(T) // sizeof(T) = sizeof(T) template struct pointee_sizeof { BOOST_STATIC_CONSTANT(int, value = ( sizeof(detail::deref_type(static_cast(0)), 0L) )); typedef boost::mpl::int_ type; }; } // namespace luabind #endif // POINTEE_SIZEOF_040211_HPP luabind-1.1.1/luabind/detail/policy.hpp000066400000000000000000000672641366245310300200420ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_POLICY_HPP_INCLUDED #define LUABIND_POLICY_HPP_INCLUDED #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef LUABIND_NO_SCOPED_ENUM # if !defined(BOOST_NO_CXX11_HDR_TYPE_TRAITS) \ && !defined(BOOST_NO_0X_HDR_TYPE_TRAITS) # include # elif BOOST_VERSION >= 105600 # include # define LUABIND_USE_BOOST_UNDERLYING_TYPE # endif #endif namespace luabind { namespace detail { struct conversion_policy_base {}; } template struct conversion_policy : detail::conversion_policy_base { BOOST_STATIC_CONSTANT(int, index = N); BOOST_STATIC_CONSTANT(bool, has_arg = HasArg); }; class index_map { public: index_map(const int* m): m_map(m) {} int operator[](int index) const { return m_map[index]; } private: const int* m_map; }; // template class functor; class weak_ref; } namespace luabind { namespace detail { template struct policy_cons { typedef H head; typedef T tail; template policy_cons > operator,(policy_cons) { return policy_cons >(); } template policy_cons > operator+(policy_cons) { return policy_cons >(); } template policy_cons > operator|(policy_cons) { return policy_cons >(); } }; struct indirection_layer { template indirection_layer(const T&); }; yes_t is_policy_cons_test(const null_type&); template yes_t is_policy_cons_test(const policy_cons&); no_t is_policy_cons_test(...); template struct is_policy_cons { static const T& t; BOOST_STATIC_CONSTANT(bool, value = sizeof(is_policy_cons_test(t)) == sizeof(yes_t)); typedef boost::mpl::bool_ type; }; template struct is_string_literal { static no_t helper(indirection_layer); static yes_t helper(const char*); }; template<> struct is_string_literal { static no_t helper(indirection_layer); }; namespace mpl = boost::mpl; template void make_pointee_instance(lua_State* L, T& x, mpl::true_, Clone) { if (get_pointer(x)) { #ifdef LUABIND_USE_CXX11 make_instance(L, std::move(x)); #else make_instance(L, x); #endif } else { lua_pushnil(L); } } template void make_pointee_instance(lua_State* L, T& x, mpl::false_, mpl::true_) { #ifdef LUABIND_USE_CXX11 std::unique_ptr ptr(new T(x)); make_instance(L, std::move(ptr)); #else std::auto_ptr ptr(new T(x)); make_instance(L, ptr); #endif } template void make_pointee_instance(lua_State* L, T& x, mpl::false_, mpl::false_) { make_instance(L, &x); } template void make_pointee_instance(lua_State* L, T& x, Clone) { make_pointee_instance(L, x, has_get_pointer(), Clone()); } // ********** pointer converter *********** struct pointer_converter { typedef pointer_converter type; typedef mpl::false_ is_native; pointer_converter() : result(0) {} void* result; int consumed_args() const { return 1; } template void apply(lua_State* L, T* ptr) { if (ptr == 0) { lua_pushnil(L); return; } if (luabind::get_back_reference(L, ptr)) return; make_instance(L, ptr); } template T* apply(lua_State*, by_pointer, int) { return static_cast(result); } template int match(lua_State* L, by_pointer, int index) { if (lua_isnil(L, index)) return 0; object_rep* obj = get_instance(L, index); if (obj == 0) return -1; if (obj->is_const()) return -1; std::pair s = obj->get_instance(registered_class::id); result = s.first; return s.second; } template void converter_postcall(lua_State*, by_pointer, int) {} }; // ******* value converter ******* struct value_converter { typedef value_converter type; typedef mpl::false_ is_native; int consumed_args() const { return 1; } value_converter() : result(0) {} void* result; template void apply(lua_State* L, T x) { if (luabind::get_back_reference(L, x)) return; make_pointee_instance(L, x, mpl::true_()); } template T apply(lua_State*, by_value, int) { return *static_cast(result); } template int match(lua_State* L, by_value, int index) { // special case if we get nil in, try to match the holder type if (lua_isnil(L, index)) return -1; object_rep* obj = get_instance(L, index); if (obj == 0) return -1; std::pair s = obj->get_instance(registered_class::id); result = s.first; return s.second; } template void converter_postcall(lua_State*, T, int) {} }; // ******* const pointer converter ******* struct const_pointer_converter { typedef const_pointer_converter type; typedef mpl::false_ is_native; int consumed_args() const { return 1; } const_pointer_converter() : result(0) {} void* result; template void apply(lua_State* L, const T* ptr) { if (ptr == 0) { lua_pushnil(L); return; } if (luabind::get_back_reference(L, ptr)) return; make_instance(L, ptr); } template T const* apply(lua_State*, by_const_pointer, int) { return static_cast(result); } template int match(lua_State* L, by_const_pointer, int index) { if (lua_isnil(L, index)) return 0; object_rep* obj = get_instance(L, index); if (obj == 0) return -1; // if the type is not one of our own registered types, classify it as a non-match std::pair s = obj->get_instance(registered_class::id); if (s.second >= 0 && !obj->is_const()) s.second += 10; result = s.first; return s.second; } template void converter_postcall(lua_State*, T, int) {} }; // ******* reference converter ******* struct ref_converter : pointer_converter { typedef ref_converter type; typedef mpl::false_ is_native; int consumed_args() const { return 1; } template void apply(lua_State* L, T& ref) { if (luabind::get_back_reference(L, ref)) return; make_pointee_instance(L, ref, mpl::false_()); } template T& apply(lua_State* L, by_reference, int index) { assert(!lua_isnil(L, index)); return *pointer_converter::apply(L, by_pointer(), index); } template int match(lua_State* L, by_reference, int index) { object_rep* obj = get_instance(L, index); if (obj == 0) return -1; if (obj->is_const()) return -1; std::pair s = obj->get_instance(registered_class::id); result = s.first; return s.second; } template void converter_postcall(lua_State*, T, int) {} }; // ******** const reference converter ********* struct const_ref_converter { typedef const_ref_converter type; typedef mpl::false_ is_native; int consumed_args() const { return 1; } const_ref_converter() : result(0) {} void* result; template void apply(lua_State* L, T const& ref) { if (luabind::get_back_reference(L, ref)) return; make_pointee_instance(L, ref, mpl::false_()); } template T const& apply(lua_State*, by_const_reference, int) { return *static_cast(result); } template int match(lua_State* L, by_const_reference, int index) { object_rep* obj = get_instance(L, index); if (obj == 0) return -1; // if the type is not one of our own registered types, classify it as a non-match std::pair s = obj->get_instance(registered_class::id); if (s.second >= 0 && !obj->is_const()) s.second += 10; result = s.first; return s.second; } template void converter_postcall(lua_State*, by_const_reference, int) { } }; // ****** enum converter ******** struct enum_converter { typedef enum_converter type; typedef mpl::true_ is_native; int consumed_args() const { return 1; } #ifdef LUABIND_NO_SCOPED_ENUM void apply(lua_State* L, int val) { lua_pushnumber(L, val); } #else template void apply(lua_State* L, T val) { typedef typename std::underlying_type::type integral_t; lua_pushnumber(L, static_cast(val)); } #endif template T apply(lua_State* L, by_value, int index) { #ifdef LUABIND_NO_SCOPED_ENUM typedef int integral_t; #elif defined(LUABIND_USE_BOOST_UNDERLYING_TYPE) typedef typename boost::underlying_type::type integral_t; #else typedef typename std::underlying_type::type integral_t; #endif return static_cast( static_cast(lua_tonumber(L, index))); } template static int match(lua_State* L, by_value, int index) { if (lua_isnumber(L, index)) return 0; else return -1; } template T apply(lua_State* L, by_const_reference, int index) { return static_cast(static_cast(lua_tonumber(L, index))); } template static int match(lua_State* L, by_const_reference, int index) { if (lua_isnumber(L, index)) return 0; else return -1; } template void converter_postcall(lua_State*, T, int) {} }; template struct value_wrapper_converter { typedef value_wrapper_converter type; typedef mpl::true_ is_native; int consumed_args() const { return 1; } template T apply(lua_State* L, by_const_reference, int index) { return T(from_stack(L, index)); } template T apply(lua_State* L, by_value, int index) { return apply(L, by_const_reference(), index); } template static int match(lua_State* L, by_const_reference, int index) { return value_wrapper_traits::check(L, index) ? (std::numeric_limits::max)() / LUABIND_MAX_ARITY : -1; } template static int match(lua_State* L, by_value, int index) { return match(L, by_const_reference(), index); } void converter_postcall(...) {} template void apply(lua_State* interpreter, T const& value_wrapper) { value_wrapper_traits::unwrap(interpreter, value_wrapper); } }; template struct default_converter_generator : mpl::eval_if< is_value_wrapper_arg , value_wrapper_converter , mpl::eval_if< boost::is_enum::type> , enum_converter , mpl::eval_if< is_nonconst_pointer , pointer_converter , mpl::eval_if< is_const_pointer , const_pointer_converter , mpl::eval_if< is_nonconst_reference , ref_converter , mpl::eval_if< is_const_reference , const_ref_converter , value_converter > > > > > > {}; } // namespace detail // *********** default_policy ***************** template struct default_converter : detail::default_converter_generator::type {}; template > struct native_converter_base { typedef boost::mpl::true_ is_native; typedef typename boost::call_traits::value_type value_type; typedef typename boost::call_traits::param_type param_type; int consumed_args() const { return 1; } template void converter_postcall(lua_State*, U const&, int) {} int match(lua_State* L, detail::by_value, int index) { return derived().compute_score(L, index); } int match(lua_State* L, detail::by_value, int index) { return derived().compute_score(L, index); } int match(lua_State* L, detail::by_const_reference, int index) { return derived().compute_score(L, index); } value_type apply(lua_State* L, detail::by_value, int index) { return derived().from(L, index); } value_type apply(lua_State* L, detail::by_value, int index) { return derived().from(L, index); } value_type apply(lua_State* L, detail::by_const_reference, int index) { return derived().from(L, index); } void apply(lua_State* L, param_type value) { derived().to(L, value); } Derived& derived() { return static_cast(*this); } }; // *********** converter for arithmetic (number) types ***************** template struct number_converter : native_converter_base< typename boost::remove_const< typename boost::remove_reference::type>::type> { template < bool is_integral, typename Traits, typename TraitsLua = boost::integer_traits > struct use_integer: boost::mpl::false_ {}; template struct use_integer: boost::mpl::bool_< Traits::const_min >= TraitsLua::const_min && Traits::const_max <= TraitsLua::const_max> {}; typedef typename boost::remove_const::type>::type T; typedef typename native_converter_base::param_type param_type; typedef typename native_converter_base::value_type value_type; typedef boost::integer_traits traits; typedef use_integer use_integer_t; lua_Number do_from(lua_State* L, int index, boost::mpl::false_) { return lua_tonumber(L, index); } lua_Integer do_from(lua_State* L, int index, boost::mpl::true_) { return lua_tointeger(L, index); } void do_to(lua_State* L, param_type value, boost::mpl::false_) { lua_pushnumber(L, static_cast(value)); } void do_to(lua_State* L, param_type value, boost::mpl::true_) { lua_pushinteger(L, static_cast(value)); } int compute_score(lua_State* L, int index) { return lua_type(L, index) == LUA_TNUMBER ? 0 : -1; } value_type from(lua_State* L, int index) { return static_cast(do_from(L, index, use_integer_t())); } void to(lua_State* L, param_type value) { do_to(L, value, use_integer_t()); } }; // template partial specialization for those types that boost knows to be // arithmetic and const references to them template struct default_converter, boost::mpl::and_< boost::is_reference, boost::is_const< typename boost::remove_reference::type >, boost::is_arithmetic< typename boost::remove_const< typename boost::remove_reference::type>::type > > > >::type > : number_converter {}; // *********** converter for bool ***************** template <> struct default_converter : native_converter_base { static int compute_score(lua_State* L, int index) { return lua_type(L, index) == LUA_TBOOLEAN ? 0 : -1; } bool from(lua_State* L, int index) { return lua_toboolean(L, index) == 1; } void to(lua_State* L, bool value) { lua_pushboolean(L, value); } }; template <> struct default_converter : default_converter {}; template <> struct default_converter : default_converter {}; #ifndef LUABIND_NO_RVALUE_REFERENCES template <> struct default_converter : default_converter {}; #endif // *********** converter for string types ***************** template <> struct default_converter : native_converter_base { static int compute_score(lua_State* L, int index) { return lua_type(L, index) == LUA_TSTRING ? 0 : -1; } std::string from(lua_State* L, int index) { return std::string(lua_tostring(L, index), lua_rawlen(L, index)); } void to(lua_State* L, std::string const& value) { lua_pushlstring(L, value.data(), value.size()); } }; template <> struct default_converter : default_converter {}; template <> struct default_converter : default_converter {}; #ifndef LUABIND_NO_RVALUE_REFERENCES template <> struct default_converter : default_converter {}; #endif template <> struct default_converter { typedef boost::mpl::true_ is_native; int consumed_args() const { return 1; } template static int match(lua_State* L, U, int index) { int type = lua_type(L, index); return (type == LUA_TSTRING || type == LUA_TNIL) ? 0 : -1; } template char const* apply(lua_State* L, U, int index) { return lua_tostring(L, index); } void apply(lua_State* L, char const* str) { lua_pushstring(L, str); } template void converter_postcall(lua_State*, U, int) {} }; template <> struct default_converter : default_converter {}; template <> struct default_converter : default_converter {}; template struct default_converter : default_converter {}; template struct default_converter : default_converter {}; // *********** converter for lua_State * arguments - consuming no explicit args ***************** template <> struct default_converter { int consumed_args() const { return 0; } template lua_State* apply(lua_State* L, U, int) { return L; } template static int match(lua_State*, U, int) { return 0; } template void converter_postcall(lua_State*, U, int) {} }; namespace detail { struct default_policy { BOOST_STATIC_CONSTANT(bool, has_arg = true); template static void precall(lua_State*, T, int) {} template struct apply { typedef default_converter type; }; }; template struct is_primitive : default_converter::is_native {}; // ============== new policy system ================= template struct find_conversion_policy; template struct find_conversion_impl { template struct apply { typedef typename find_conversion_policy::type type; }; }; template<> struct find_conversion_impl { template struct apply { typedef typename Policies::head head; typedef typename Policies::tail tail; BOOST_STATIC_CONSTANT(bool, found = (N == head::index)); typedef typename boost::mpl::if_c::type >::type type; }; }; template struct find_conversion_impl2 { template struct apply : find_conversion_impl< boost::is_base_and_derived::value >::template apply { }; }; template<> struct find_conversion_impl2 { template struct apply { typedef default_policy type; }; }; template struct find_conversion_policy : find_conversion_impl2::template apply { }; template struct policy_list_postcall { typedef typename List::head head; typedef typename List::tail tail; static void apply(lua_State* L, const index_map& i) { head::postcall(L, i); policy_list_postcall::apply(L, i); } }; template<> struct policy_list_postcall { static void apply(lua_State*, const index_map&) {} }; // ================================================== // ************** precall and postcall on policy_cons ********************* template struct policy_precall { typedef typename List::head head; typedef typename List::tail tail; static void apply(lua_State* L, int index) { head::precall(L, index); policy_precall::apply(L, index); } }; template<> struct policy_precall { static void apply(lua_State*, int) {} }; template struct policy_postcall { typedef typename List::head head; typedef typename List::tail tail; static void apply(lua_State* L, int index) { head::postcall(L, index); policy_postcall::apply(L, index); } }; template<> struct policy_postcall { static void apply(lua_State*, int) {} }; template struct has_policy : mpl::if_< boost::is_same , mpl::true_ , has_policy >::type {}; template struct has_policy : mpl::false_ {}; }} // namespace luabind::detail namespace luabind { namespace { #if defined(__GNUC__) && ( \ (BOOST_VERSION < 103500) \ || (BOOST_VERSION < 103900 && (__GNUC__ * 100 + __GNUC_MINOR__ <= 400)) \ || (__GNUC__ * 100 + __GNUC_MINOR__ < 400)) static inline boost::arg<0> return_value() { return boost::arg<0>(); } static inline boost::arg<0> result() { return boost::arg<0>(); } # define LUABIND_PLACEHOLDER_ARG(N) boost::arg(*)() #elif defined(BOOST_MSVC) || defined(__MWERKS__) \ || (BOOST_VERSION >= 103900 && defined(__GNUC__) \ && (__GNUC__ * 100 + __GNUC_MINOR__ == 400)) static boost::arg<0> return_value; static boost::arg<0> result; # define LUABIND_PLACEHOLDER_ARG(N) boost::arg #else boost::arg<0> return_value; boost::arg<0> result; # define LUABIND_PLACEHOLDER_ARG(N) boost::arg #endif }} #endif // LUABIND_POLICY_HPP_INCLUDED luabind-1.1.1/luabind/detail/primitives.hpp000066400000000000000000000035001366245310300207150ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_PRIMITIVES_HPP_INCLUDED #define LUABIND_PRIMITIVES_HPP_INCLUDED #include #include #include namespace luabind { namespace detail { template struct type_ {}; struct null_type {}; struct lua_to_cpp {}; struct cpp_to_lua {}; template struct by_value {}; template struct by_reference {}; template struct by_const_reference {}; template struct by_pointer {}; template struct by_const_pointer {}; struct ltstr { bool operator()(const char* s1, const char* s2) const { return std::strcmp(s1, s2) < 0; } }; }} #endif // LUABIND_PRIMITIVES_HPP_INCLUDED luabind-1.1.1/luabind/detail/property.hpp000066400000000000000000000014161366245310300204120ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_PROPERTY_081020_HPP # define LUABIND_PROPERTY_081020_HPP namespace luabind { namespace detail { template struct access_member_ptr { access_member_ptr(T Class::* mem_ptr_) : mem_ptr(mem_ptr_) {} Result operator()(Class const& x) const { return const_cast(x).*mem_ptr; } void operator()(Class& x, T const& value) const { x.*mem_ptr = value; } T Class::* mem_ptr; }; }} // namespace luabind::detail #endif // LUABIND_PROPERTY_081020_HPP luabind-1.1.1/luabind/detail/signature_match.hpp000066400000000000000000000041731366245310300217060ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_SIGNATURE_MATCH_HPP_INCLUDED #define LUABIND_SIGNATURE_MATCH_HPP_INCLUDED #include #include #include #include #include #include #include #include #include namespace luabind { namespace adl { class argument; } template struct constructor { typedef BOOST_PP_CAT( boost::mpl::vector, BOOST_PP_INC(BOOST_PP_INC(LUABIND_MAX_ARITY)))< void, argument const&, BOOST_PP_ENUM_PARAMS(LUABIND_MAX_ARITY, A) > signature0; typedef typename boost::mpl::remove< signature0, detail::null_type>::type signature; }; } #endif // LUABIND_SIGNATURE_MATCH_HPP_INCLUDED luabind-1.1.1/luabind/detail/stack_utils.hpp000066400000000000000000000031501366245310300210500ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_STACK_UTILS_HPP_INCLUDED #define LUABIND_STACK_UTILS_HPP_INCLUDED #include #include namespace luabind { namespace detail { struct stack_pop { stack_pop(lua_State* L, int n) : m_state(L) , m_n(n) { } ~stack_pop() { lua_pop(m_state, m_n); } private: lua_State* m_state; int m_n; }; }} #endif // LUABIND_STACK_UTILS_HPP_INCLUDED luabind-1.1.1/luabind/detail/typetraits.hpp000066400000000000000000000124771366245310300207470ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_TYPETRAITS_HPP_INCLUDED #define LUABIND_TYPETRAITS_HPP_INCLUDED #include #include #include #include #include #include namespace luabind { namespace detail { #ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION template struct is_const_type { typedef typename boost::mpl::if_ , yes_t , no_t >::type type; }; template struct is_const_reference_helper { template struct apply { enum { value = false }; }; }; template typename is_const_type::type is_const_reference_tester(T&); no_t is_const_reference_tester(...); template<> struct is_const_reference_helper { template struct apply { static T getT(); enum { value = sizeof(is_const_reference_tester(getT())) == sizeof(yes_t) }; }; }; template struct is_const_reference : is_const_reference_helper::value>::template apply { typedef boost::mpl::bool_ type; }; template struct is_nonconst_reference { enum { value = boost::is_reference::value && !is_const_reference::value }; typedef boost::mpl::bool_ type; }; #else template struct is_const_reference { enum { value = false }; typedef boost::mpl::bool_ type; }; template struct is_const_reference { enum { value = true }; typedef boost::mpl::bool_ type; }; template struct is_nonconst_reference { enum { value = false }; typedef boost::mpl::bool_ type; }; template struct is_nonconst_reference { enum { value = !is_const_reference::value }; typedef boost::mpl::bool_ type; }; #endif template yes_t is_const_pointer_helper(void(*)(const A*)); no_t is_const_pointer_helper(...); template struct is_const_pointer { enum { value = sizeof(is_const_pointer_helper(static_cast(0))) == sizeof(yes_t) }; typedef boost::mpl::bool_ type; }; template yes_t is_nonconst_pointer_helper(void(*)(A*)); no_t is_nonconst_pointer_helper(...); template struct is_nonconst_pointer { enum { value = sizeof(is_nonconst_pointer_helper(static_cast(0))) == sizeof(yes_t) && !is_const_pointer::value }; typedef boost::mpl::bool_ type; }; /* template struct is_constructable_from_helper { static yes_t check(const T&); static no_t check(...); }; template struct is_constructable_from { static From getFrom(); enum { value = sizeof(is_constructable_from_helper::check(getFrom())) == sizeof(yes_t) }; }; template struct is_const_member_function_helper { static no_t test(...); template static yes_t test(R(T::*)() const); template static yes_t test(R(T::*)(A1) const); template static yes_t test(R(T::*)(A1,A2) const); template static yes_t test(R(T::*)(A1,A2,A3) const); }; template struct is_const_member_function { static U getU(); enum { value = sizeof(is_const_member_function_helper::test(getU())) == sizeof(yes_t) }; }; */ template struct max_c { enum { value = (v1>v2)?v1:v2 }; }; }} #endif // LUABIND_TYPETRAITS_HPP_INCLUDED luabind-1.1.1/luabind/detail/yes_no.hpp000066400000000000000000000024541366245310300200250ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin // 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. #ifndef YES_NO_040211_HPP #define YES_NO_040211_HPP namespace luabind { namespace detail { typedef char(&yes_t)[1]; typedef char(&no_t)[2]; }} // namespace luabind::detail #endif // YES_NO_040211_HPP luabind-1.1.1/luabind/discard_result_policy.hpp000066400000000000000000000047201366245310300216530ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_DISCARD_RESULT_POLICY_HPP_INCLUDED #define LUABIND_DISCARD_RESULT_POLICY_HPP_INCLUDED #include #include // for index_map, etc #include // for null_type, etc #include // for if_ #include // for is_same #include namespace luabind { namespace detail { struct discard_converter { template void apply(lua_State*, T) {} }; struct discard_result_policy : conversion_policy<0> { static void precall(lua_State*, const index_map&) {} static void postcall(lua_State*, const index_map&) {} struct can_only_convert_from_cpp_to_lua {}; template struct apply { typedef typename boost::mpl::if_ , discard_converter , can_only_convert_from_cpp_to_lua >::type type; }; }; }} namespace luabind { detail::policy_cons< detail::discard_result_policy, detail::null_type> const discard_result = {}; namespace detail { inline void ignore_unused_discard_result() { (void)discard_result; } } } #endif // LUABIND_DISCARD_RESULT_POLICY_HPP_INCLUDED luabind-1.1.1/luabind/error.hpp000066400000000000000000000064211366245310300164160ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_ERROR_HPP_INCLUDED #define LUABIND_ERROR_HPP_INCLUDED #include #include #include #include #ifndef LUABIND_NO_EXCEPTIONS #include #endif #include namespace luabind { #ifndef LUABIND_NO_EXCEPTIONS // this exception usually means that the lua function you called // from C++ failed with an error code. You will have to // read the error code from the top of the lua stack // the reason why this exception class doesn't contain // the message itself is that std::string's copy constructor // may throw, if the copy constructor of an exception that is // being thrown throws another exception, terminate will be called // and the entire application is killed. class LUABIND_API error : public std::exception { public: explicit error(lua_State* L): m_L(L) {} lua_State* state() const LUABIND_NOEXCEPT { return m_L; } virtual const char* what() const LUABIND_NOEXCEPT { return "lua runtime error"; } private: lua_State* m_L; }; // if an object_cast<>() fails, this is thrown // it is also thrown if the return value of // a lua function cannot be converted class LUABIND_API cast_failed : public std::exception { public: cast_failed(lua_State* L, type_id const& i): m_L(L), m_info(i) {} lua_State* state() const LUABIND_NOEXCEPT { return m_L; } type_id info() const LUABIND_NOEXCEPT { return m_info; } virtual const char* what() const LUABIND_NOEXCEPT { return "unable to make cast"; } private: lua_State* m_L; type_id m_info; }; #else LUABIND_API void set_error_callback(error_callback_fun e); LUABIND_API void set_cast_failed_callback(cast_failed_callback_fun c); LUABIND_API error_callback_fun get_error_callback(); LUABIND_API cast_failed_callback_fun get_cast_failed_callback(); #endif LUABIND_API void set_pcall_callback(pcall_callback_fun e); LUABIND_API pcall_callback_fun get_pcall_callback(); } #endif // LUABIND_ERROR_HPP_INCLUDED luabind-1.1.1/luabind/error_callback_fun.hpp000066400000000000000000000033261366245310300211030ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef INCLUDED_error_callback_fun_hpp_GUID_1150976a_4348_495f_99ce_9d7edd00a0b8 #define INCLUDED_error_callback_fun_hpp_GUID_1150976a_4348_495f_99ce_9d7edd00a0b8 // Internal Includes #include // Library/third-party includes #include // Standard includes // - none namespace luabind { class type_id; typedef void(*error_callback_fun)(lua_State*); typedef void(*cast_failed_callback_fun)(lua_State*, type_id const&); typedef int(*pcall_callback_fun)(lua_State*); } #endif // INCLUDED_error_callback_fun_hpp_GUID_1150976a_4348_495f_99ce_9d7edd00a0b8 luabind-1.1.1/luabind/exception_handler.hpp000066400000000000000000000040461366245310300207610ustar00rootroot00000000000000// Copyright Daniel Wallin 2005. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_EXCEPTION_HANDLER_050601_HPP # define LUABIND_EXCEPTION_HANDLER_050601_HPP # include // for LUABIND_API # include // for optional # include # include namespace luabind { # ifndef LUABIND_NO_EXCEPTIONS namespace detail { struct LUABIND_API exception_handler_base { exception_handler_base() : next(0) {} virtual ~exception_handler_base() {} virtual void handle(lua_State*) const = 0; void try_next(lua_State*) const; exception_handler_base* next; }; template struct exception_handler : exception_handler_base { typedef E const& argument; exception_handler(Handler handler_) : handler(handler_) {} void handle(lua_State* L) const { try { try_next(L); } catch (argument e) { handler(L, e); } } Handler handler; }; LUABIND_API void handle_exception_aux(lua_State* L); LUABIND_API void register_exception_handler(exception_handler_base*); } // namespace detail # endif template void register_exception_handler(Handler handler, boost::type* = 0) { # ifndef LUABIND_NO_EXCEPTIONS detail::register_exception_handler( new detail::exception_handler(handler) ); # endif } template boost::optional handle_exceptions(lua_State* L, F fn, boost::type* = 0) { # ifndef LUABIND_NO_EXCEPTIONS try { return fn(); } catch (...) { detail::handle_exception_aux(L); } return boost::optional(); # else return fn(); # endif } } // namespace luabind #endif // LUABIND_EXCEPTION_HANDLER_050601_HPP luabind-1.1.1/luabind/from_stack.hpp000066400000000000000000000027151366245310300174170ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_FROM_STACK_050715_HPP #define LUABIND_FROM_STACK_050715_HPP #include namespace luabind { struct from_stack { from_stack(lua_State* L, int idx) : interpreter(L) , index(idx) {} lua_State* interpreter; int index; }; } // namespace luabind #endif // LUABIND_FROM_STACK_050715_HPP luabind-1.1.1/luabind/function.hpp000066400000000000000000000027571366245310300171220ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_FUNCTION2_081014_HPP # define LUABIND_FUNCTION2_081014_HPP # include # include # include namespace luabind { namespace detail { template struct function_registration : registration { function_registration(char const* name_, F f_, Policies const& policies_) : name(name_) , f(f_) , policies(policies_) {} void register_(lua_State* L) const { object fn = make_function(L, f, deduce_signature(f), policies); add_overload( object(from_stack(L, -1)) , name , fn ); } char const* name; F f; Policies policies; }; } // namespace detail template scope def(char const* name, F f, Policies const& policies) { #ifdef LUABIND_USE_CXX11 return scope(std::unique_ptr( #else return scope(std::auto_ptr( #endif new detail::function_registration(name, f, policies))); } template scope def(char const* name, F f) { return def(name, f, detail::null_type()); } } // namespace luabind #endif // LUABIND_FUNCTION2_081014_HPP luabind-1.1.1/luabind/function_converter.hpp000066400000000000000000000076651366245310300212140ustar00rootroot00000000000000// Copyright Christian Neumller 2013. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !BOOST_PP_IS_ITERATING # ifndef LUABIND_FUNCTION_CONVERTER_HPP_INCLUDED # define LUABIND_FUNCTION_CONVERTER_HPP_INCLUDED # include # include # include # include # include namespace luabind { template struct function { typedef R result_type; function(luabind::object const& obj) : m_func(obj) { } R operator() () { return call_function(m_func); } # define BOOST_PP_ITERATION_LIMITS (1, LUABIND_MAX_ARITY) # define BOOST_PP_FILENAME_1 // include self # include BOOST_PP_ITERATE() private: object m_func; }; template <> struct function { typedef void result_type; function(luabind::object const& obj) : m_func(obj) { } void operator() () { call_function(m_func); } # define VOID_SPEC # define BOOST_PP_ITERATION_LIMITS (1, LUABIND_MAX_ARITY) # define BOOST_PP_FILENAME_1 // include self # include BOOST_PP_ITERATE() # undef VOID_SPEC private: luabind::object m_func; }; template struct default_converter >::type> { typedef boost::mpl::true_ is_native; int consumed_args() const { return 1; } template void converter_postcall(lua_State*, U const&, int) {} template static int match(lua_State* L, U, int index) { if (lua_type(L, index) == LUA_TFUNCTION) return 0; if (luaL_getmetafield(L, index, "__call")) { lua_pop(L, 1); return 1; } return -1; } template F apply(lua_State* L, U, int index) { // If you get a compiler error here, you are probably trying to // get a function pointer from Lua. This is not supported: // you must use a type which is constructible from a // luabind::function, e.g. std::function or boost::function. return function( object(from_stack(L, index))); } void apply(lua_State* L, F value) { make_function(L, value).push(L); } }; } // namespace luabind # endif // LUABIND_FUNCTION_CONVERTER_HPP_INCLUDED #else // !BOOST_PP_IS_ITERATING # define N BOOST_PP_ITERATION() # define TMPL_PARAMS BOOST_PP_ENUM_PARAMS(N, typename A) # ifndef LUABIND_NO_RVALUE_REFERENCES # define TYPED_ARGS BOOST_PP_ENUM_BINARY_PARAMS(N, A, && a) # else # define TYPED_ARGS BOOST_PP_ENUM_BINARY_PARAMS(N, A, const& a) # endif # ifndef LUABIND_NO_RVALUE_REFERENCES # define PRINT_FORWARD_ARG(z, n, _) std::forward(BOOST_PP_CAT(a, n)) # define TRAILING_ARGS BOOST_PP_ENUM_TRAILING(N, PRINT_FORWARD_ARG, ~) # else # define TRAILING_ARGS BOOST_PP_ENUM_TRAILING_PARAMS(N, a) # endif # ifdef VOID_SPEC template void operator() (TYPED_ARGS) { luabind::call_function(m_func TRAILING_ARGS); } # else template R operator() (TYPED_ARGS) { return luabind::call_function(m_func TRAILING_ARGS); } # endif # undef TMPL_PARAMS # undef TYPED_ARGS # undef TRAILING_ARGS # undef N #endif // BOOST_PP_IS_ITERATING luabind-1.1.1/luabind/function_introspection.hpp000066400000000000000000000036351366245310300220760ustar00rootroot00000000000000/** @file @brief Header @date 2012 @author Ryan Pavlik and http://academic.cleardefinition.com/ Iowa State University Virtual Reality Applications Center Human-Computer Interaction Graduate Program */ // Copyright Iowa State University 2012. // 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. #pragma once #ifndef INCLUDED_function_introspection_hpp_GUID_b55783e7_e6da_4816_925e_9256245c1065 #define INCLUDED_function_introspection_hpp_GUID_b55783e7_e6da_4816_925e_9256245c1065 // Internal Includes #include // Library/third-party includes #include // Standard includes // - none namespace luabind { LUABIND_API int bind_function_introspection(lua_State * L); } // end of namespace luabind #endif // INCLUDED_function_introspection_hpp_GUID_b55783e7_e6da_4816_925e_9256245c1065 luabind-1.1.1/luabind/get_main_thread.hpp000066400000000000000000000010121366245310300203660ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_GET_MAIN_THREAD_090321_HPP # define LUABIND_GET_MAIN_THREAD_090321_HPP # include # include namespace luabind { LUABIND_API lua_State* get_main_thread(lua_State* L); } // namespace luabind #endif // LUABIND_GET_MAIN_THREAD_090321_HPP luabind-1.1.1/luabind/get_pointer.hpp000066400000000000000000000030221366245310300175760ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin // 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. #ifndef LUABIND_GET_POINTER_051023_HPP # define LUABIND_GET_POINTER_051023_HPP // // We need these overloads in the luabind namespace. // # include namespace luabind { using boost::get_pointer; #ifdef LUABIND_USE_CXX11 template T* get_pointer(std::unique_ptr const& ptr) { return ptr.get(); } #endif } // namespace luabind #endif // LUABIND_GET_POINTER_051023_HPP luabind-1.1.1/luabind/handle.hpp000066400000000000000000000101721366245310300165160ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_HANDLE_050420_HPP #define LUABIND_HANDLE_050420_HPP #include #include #include #include #include namespace luabind { // A reference to a Lua value. Represents an entry in the // registry table. class handle { public: handle(); handle(lua_State* L, int stack_index); handle(lua_State* main, lua_State* L, int stack_index); handle(handle const& other); ~handle(); handle& operator=(handle const& other); void swap(handle& other); void push(lua_State* L) const; lua_State* interpreter() const; bool is_valid() const; void replace(lua_State* L, int stack_index); void pop(lua_State* L); void reset(); private: lua_State* m_interpreter; int m_index; }; inline handle::handle() : m_interpreter(0) , m_index(LUA_NOREF) {} inline handle::handle(handle const& other) : m_interpreter(other.m_interpreter) , m_index(LUA_NOREF) { if (m_interpreter == 0) return; other.push(m_interpreter); m_index = luaL_ref(m_interpreter, LUA_REGISTRYINDEX); } inline handle::handle(lua_State* L, int stack_index) : m_interpreter(L) , m_index(LUA_NOREF) { lua_pushvalue(L, stack_index); m_index = luaL_ref(L, LUA_REGISTRYINDEX); } inline handle::handle(lua_State* main, lua_State* L, int stack_index) : m_interpreter(main) , m_index(LUA_NOREF) { lua_pushvalue(L, stack_index); m_index = luaL_ref(L, LUA_REGISTRYINDEX); } inline handle::~handle() { if (is_valid()) luaL_unref(m_interpreter, LUA_REGISTRYINDEX, m_index); } inline handle& handle::operator=(handle const& other) { handle(other).swap(*this); return *this; } inline void handle::swap(handle& other) { std::swap(m_interpreter, other.m_interpreter); std::swap(m_index, other.m_index); } inline void handle::push(lua_State* L) const { lua_rawgeti(L, LUA_REGISTRYINDEX, m_index); } inline lua_State* handle::interpreter() const { return m_interpreter; } inline bool handle::is_valid() const { if (m_index == LUA_NOREF) { assert(!m_interpreter); return false; } else { assert(m_interpreter); return true; } } inline void handle::replace(lua_State* L, int stack_index) { lua_pushvalue(L, stack_index); lua_rawseti(L, LUA_REGISTRYINDEX, m_index); } inline void handle::reset() { if (is_valid()) { luaL_unref(m_interpreter, LUA_REGISTRYINDEX, m_index); m_index = LUA_NOREF; } } inline void handle::pop(lua_State* L) { reset(); m_interpreter = L; m_index = luaL_ref(L, LUA_REGISTRYINDEX); } template<> struct value_wrapper_traits { typedef boost::mpl::true_ is_specialized; static lua_State* interpreter(handle const& value) { return value.interpreter(); } static void unwrap(lua_State* L, handle const& value) { value.push(L); } static bool check(...) { return true; } }; } // namespace luabind #endif // LUABIND_HANDLE_050420_HPP luabind-1.1.1/luabind/intrusive_ptr_converter.hpp000066400000000000000000000033751366245310300222760ustar00rootroot00000000000000// Copyright Chsritian Neumüller 2013. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_INTRUSIVE_PTR_CONVERTER_HPP_INCLUDED #define LUABIND_INTRUSIVE_PTR_CONVERTER_HPP_INCLUDED #include #include #include #include #include namespace luabind { namespace detail { template struct intrusive_ptr_converter : default_converter { private: typedef P ptr_t; typedef typename ptr_t::element_type* rawptr_t; public: typedef mpl::false_ is_native; template int match(lua_State* L, U, int index) { return default_converter::match( L, LUABIND_DECORATE_TYPE(rawptr_t), index); } template ptr_t apply(lua_State* L, U, int index) { rawptr_t raw_ptr = default_converter::apply( L, LUABIND_DECORATE_TYPE(rawptr_t), index); return ptr_t(raw_ptr); } void apply(lua_State* L, ptr_t const& p) { detail::value_converter().apply(L, p); } template void converter_postcall(lua_State*, U const&, int) {} }; } // namespace detail template struct default_converter >: detail::intrusive_ptr_converter > {}; template struct default_converter const&>: detail::intrusive_ptr_converter > {}; } // namespace luabind #endif // LUABIND_INTRUSIVE_PTR_CONVERTER_HPP_INCLUDED luabind-1.1.1/luabind/iterator_policy.hpp000066400000000000000000000056461366245310300205050ustar00rootroot00000000000000// Copyright Daniel Wallin 2007. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_ITERATOR_POLICY_071111_HPP # define LUABIND_ITERATOR_POLICY_071111_HPP # include // for LUABIND_ANONYMOUS_FIX # include // for convert_to_lua # include // for index_map, etc # include // for operator new namespace luabind { namespace detail { struct null_type; template struct iterator { static int next(lua_State* L) { iterator* self = static_cast( lua_touserdata(L, lua_upvalueindex(1))); if (self->first != self->last) { convert_to_lua(L, *self->first); ++self->first; } else { lua_pushnil(L); } return 1; } static int destroy(lua_State* L) { iterator* self = static_cast(lua_touserdata(L, 1)); self->~iterator(); (void)self; // MSVC warns about self not being referenced. return 0; } iterator(Iterator first_, Iterator last_) : first(first_) , last(last_) {} Iterator first; Iterator last; }; template int make_range(lua_State* L, Iterator first, Iterator last) { void* storage = lua_newuserdata(L, sizeof(iterator)); lua_createtable(L, 0, 1); lua_pushcclosure(L, iterator::destroy, 0); lua_setfield(L, -2, "__gc"); lua_setmetatable(L, -2); lua_pushcclosure(L, iterator::next, 1); new (storage) iterator(first, last); return 1; } template int make_range(lua_State* L, Container& container) { return make_range(L, container.begin(), container.end()); } struct iterator_converter { typedef iterator_converter type; template void apply(lua_State* L, Container& container) { make_range(L, container); } template void apply(lua_State* L, Container const& container) { make_range(L, container); } }; struct iterator_policy : conversion_policy<0> { static void precall(lua_State*, index_map const&) {} static void postcall(lua_State*, index_map const&) {} template struct apply { typedef iterator_converter type; }; }; }} // namespace luabind::detail namespace luabind { detail::policy_cons const return_stl_iterator = {}; namespace detail { inline void ignore_unused_return_stl_iterator() { (void)return_stl_iterator; } } } // namespace luabind #endif // LUABIND_ITERATOR_POLICY__071111_HPP luabind-1.1.1/luabind/lua_include.hpp000066400000000000000000000051511366245310300175500ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_LUA_INCLUDE_HPP_INCLUDED #define LUABIND_LUA_INCLUDE_HPP_INCLUDED #include #ifndef LUABIND_CPLUSPLUS_LUA extern "C" { #endif #include "lua.h" #include "lauxlib.h" #ifndef LUABIND_CPLUSPLUS_LUA } #endif #if LUA_VERSION_NUM < 502 # define lua_compare(L, index1, index2, fn) fn(L, index1, index2) # define LUA_OPEQ lua_equal # define LUA_OPLT lua_lessthan # define lua_rawlen lua_objlen # define lua_pushglobaltable(L) lua_pushvalue(L, LUA_GLOBALSINDEX) # define lua_getuservalue lua_getfenv # define lua_setuservalue lua_setfenv # define LUA_OK 0 namespace luabind { namespace detail { inline bool is_relative_index(int idx) { return idx < 0 && idx > LUA_REGISTRYINDEX; } } } // namespace apollo::detail LUABIND_API char const* luaL_tolstring(lua_State* L, int idx, size_t* len); inline int lua_absindex(lua_State* L, int idx) { return luabind::detail::is_relative_index(idx) ? lua_gettop(L) + idx + 1 : idx; } inline void lua_rawsetp(lua_State* L, int t, void const* k) { lua_pushlightuserdata(L, const_cast(k)); lua_insert(L, -2); // Move key beneath value. if (luabind::detail::is_relative_index(t)) t -= 1; // Adjust for pushed k. lua_rawset(L, t); } inline void lua_rawgetp(lua_State* L, int t, void const* k) { lua_pushlightuserdata(L, const_cast(k)); if (luabind::detail::is_relative_index(t)) t -= 1; // Adjust for pushed k. lua_rawget(L, t); } #endif #endif // LUABIND_LUA_INCLUDE_HPP_INCLUDED luabind-1.1.1/luabind/lua_state_fwd.hpp000066400000000000000000000025151366245310300201060ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_LUA_STATE_FWD_HPP #define LUABIND_LUA_STATE_FWD_HPP #ifndef LUABIND_CPLUSPLUS_LUA extern "C" { #endif struct lua_State; #ifndef LUABIND_CPLUSPLUS_LUA } #endif #endif // LUABIND_BACK_REFERENCE_FWD_040510_HPP luabind-1.1.1/luabind/luabind.hpp000066400000000000000000000025141366245310300167020ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_BIND_HPP_INCLUDED #define LUABIND_BIND_HPP_INCLUDED #include #include #include #include #endif // LUABIND_BIND_HPP_INCLUDED luabind-1.1.1/luabind/make_function.hpp000066400000000000000000000062461366245310300201140ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_MAKE_FUNCTION_081014_HPP # define LUABIND_MAKE_FUNCTION_081014_HPP # include # include # include # include # include # include namespace luabind { namespace detail { LUABIND_API bool is_luabind_function(lua_State* L, int index); // MSVC complains about member being sensitive to alignment (C4121) // when F is a pointer to member of a class with virtual bases. # ifdef BOOST_MSVC # pragma pack(push) # pragma pack(16) # endif template struct function_object_impl : function_object { function_object_impl(F f_, Policies const& policies_) : function_object(&entry_point) , f(f_) , policies(policies_) {} int call(lua_State* L, invoke_context& ctx) const { return invoke(L, *this, ctx, f, Signature(), policies); } void format_signature(lua_State* L, char const* function) const { detail::format_signature(L, function, Signature()); } static int entry_point(lua_State* L) { function_object_impl const* impl = *static_cast( lua_touserdata(L, lua_upvalueindex(1))); int results = 0; bool error = false; # ifndef LUABIND_NO_EXCEPTIONS try #endif // Scope neeeded to destroy invoke_context before calling lua_error() { invoke_context ctx; results = invoke( L, *impl, ctx, impl->f, Signature(), impl->policies); if (!ctx) { ctx.format_error(L, impl); error = true; } } #ifndef LUABIND_NO_EXCEPTIONS catch (...) { error = true; handle_exception_aux(L); } #endif if (error) { assert(results >= 0); return lua_error(L); } if (results < 0) { return lua_yield(L, -results - 1); } return results; } F f; Policies policies; }; # ifdef BOOST_MSVC # pragma pack(pop) # endif LUABIND_API object make_function_aux( lua_State* L, function_object* impl ); LUABIND_API void add_overload(object const&, char const*, object const&); } // namespace detail template object make_function(lua_State* L, F f, Signature, Policies) { return detail::make_function_aux( L , new detail::function_object_impl( f, Policies() ) ); } template object make_function(lua_State* L, F f) { return make_function(L, f, detail::deduce_signature(f), detail::null_type()); } } // namespace luabind #endif // LUABIND_MAKE_FUNCTION_081014_HPP luabind-1.1.1/luabind/nil.hpp000066400000000000000000000025301366245310300160440ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_NIL_HPP #define LUABIND_NIL_HPP #include namespace luabind { namespace detail { struct nil_type {}; } // defined in class.cpp LUABIND_API extern detail::nil_type nil; } #endif luabind-1.1.1/luabind/no_dependency.hpp000066400000000000000000000016071366245310300201000ustar00rootroot00000000000000// Copyright Daniel Wallin 2010. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_NO_DEPENDENCY_100324_HPP # define LUABIND_NO_DEPENDENCY_100324_HPP # include namespace luabind { namespace detail { struct no_dependency_policy { static void precall(lua_State*, index_map const&) {} static void postcall(lua_State*, index_map const&) {} }; typedef policy_cons no_dependency_node; } // namespace detail detail::no_dependency_node const no_dependency = {}; namespace detail { inline void ignore_unused_no_dependency() { (void)no_dependency; } } // namespace detail } // namespace luabind #endif // LUABIND_NO_DEPENDENCY_100324_HPP luabind-1.1.1/luabind/object.hpp000066400000000000000000000024131366245310300165300ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_OBJECT_HPP #define LUABIND_OBJECT_HPP #include #include #endif // LUABIND_OBJECT_HPP luabind-1.1.1/luabind/object_fwd.hpp000066400000000000000000000005131366245310300173670ustar00rootroot00000000000000#ifndef LUABIND_OBJECT_FWD_050419_HPP #define LUABIND_OBJECT_FWD_050419_HPP namespace luabind { namespace adl { class object; class argument; template struct table; } // namespace adl using adl::object; using adl::argument; using adl::table; } // namespace luabind #endif luabind-1.1.1/luabind/open.hpp000066400000000000000000000025331366245310300162260ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_OPEN_HPP_INCLUDED #define LUABIND_OPEN_HPP_INCLUDED #include #include namespace luabind { LUABIND_API void open(lua_State* L); } #endif // LUABIND_OPEN_HPP_INCLUDED luabind-1.1.1/luabind/operator.hpp000066400000000000000000000214411366245310300171170ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #ifndef OPERATOR_040729_HPP #define OPERATOR_040729_HPP #include #include #include #include #include #include #include #include #include #include #if defined(__GNUC__) && __GNUC__ < 3 # define LUABIND_NO_STRINGSTREAM #else # if defined(BOOST_NO_STRINGSTREAM) # define LUABIND_NO_STRINGSTREAM # endif #endif #ifdef LUABIND_NO_STRINGSTREAM #include #else #include #endif namespace luabind { namespace detail { template struct unwrap_parameter_type; template struct operator_ {}; struct operator_void_return {}; template inline T const& operator,(T const& x, operator_void_return) { return x; } }} // namespace luabind #include namespace luabind { namespace operators { #define BOOST_PP_ITERATION_PARAMS_1 (3, \ (0, LUABIND_MAX_ARITY, )) #include BOOST_PP_ITERATE() }} // namespace luabind::operators #include namespace luabind { template struct self_base { operators::call_operator0 operator()() const { return 0; } #define BOOST_PP_LOCAL_MACRO(n) \ template \ BOOST_PP_CAT(operators::call_operator, n)< \ Derived \ BOOST_PP_ENUM_TRAILING_PARAMS(n, A) \ >\ operator()( \ BOOST_PP_ENUM_BINARY_PARAMS(n, A, const& BOOST_PP_INTERCEPT) \ ) const \ { \ return 0; \ } #define BOOST_PP_LOCAL_LIMITS (1, LUABIND_MAX_ARITY) #include BOOST_PP_LOCAL_ITERATE() }; struct self_type : self_base { }; struct const_self_type : self_base { }; namespace detail { template struct unwrap_parameter_type { typedef typename boost::mpl::eval_if< boost::is_same , boost::mpl::identity , boost::mpl::eval_if< boost::is_same , boost::mpl::identity , unwrap_other > >::type type; }; template struct binary_operator : operator_ > { binary_operator(int) {} template struct apply { typedef typename unwrap_parameter_type::type arg0; typedef typename unwrap_parameter_type::type arg1; static void execute(lua_State* L, arg0 _0, arg1 _1) { Derived::template apply::execute( L, _0, _1); } }; static char const* name() { return Derived::name(); } }; template struct unary_operator : operator_ > { unary_operator(int) {} template struct apply { typedef typename unwrap_parameter_type::type arg0; static void execute(lua_State* L, arg0 _0) { Derived::template apply::execute(L, _0); } }; static char const* name() { return Derived::name(); } }; template inline void operator_result(lua_State*, operator_void_return, Policies*) { } namespace mpl = boost::mpl; template inline void operator_result(lua_State* L, T const& x, Policies*) { typedef typename find_conversion_policy< 0 , Policies >::type cv_policy; typename mpl::apply_wrap2::type cv; cv.apply(L, x); } }} // namespace detail::luabind namespace luabind { #define LUABIND_BINARY_OPERATOR(name_, op) \ namespace operators { \ \ struct name_ \ { \ template \ struct apply \ { \ static void execute(lua_State* L, T0 _0, T1 _1) \ { \ detail::operator_result(L, _0 op _1, static_cast(0)); \ } \ }; \ \ static char const* name() \ { \ return "__" # name_; \ } \ }; \ \ } \ \ template \ detail::binary_operator< \ operators::name_ \ , U \ , T \ > \ inline operator op(self_base, T const&) \ { \ return 0; \ } \ \ template \ detail::binary_operator< \ operators::name_ \ , T \ , U \ > \ inline operator op(T const&, self_base) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , self_type \ , self_type \ > \ inline operator op(self_type, self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , self_type \ , const_self_type \ > \ inline operator op(self_type, const_self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , const_self_type \ , self_type \ > \ inline operator op(const_self_type, self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , const_self_type \ , const_self_type \ > \ inline operator op(const_self_type, const_self_type) \ { \ return 0; \ } LUABIND_BINARY_OPERATOR(add, +) LUABIND_BINARY_OPERATOR(sub, -) LUABIND_BINARY_OPERATOR(mul, *) LUABIND_BINARY_OPERATOR(div, /) LUABIND_BINARY_OPERATOR(mod, %) LUABIND_BINARY_OPERATOR(pow, ^) LUABIND_BINARY_OPERATOR(lt, <) LUABIND_BINARY_OPERATOR(le, <=) LUABIND_BINARY_OPERATOR(eq, ==) #undef LUABIND_BINARY_OPERATOR #define LUABIND_UNARY_OPERATOR(name_, op, fn) \ namespace operators { \ \ struct name_ \ { \ template \ struct apply \ { \ static void execute(lua_State* L, T x) \ { \ detail::operator_result(L, op(x), static_cast(0)); \ } \ }; \ \ static char const* name() \ { \ return "__" # name_; \ } \ }; \ \ } \ \ template \ detail::unary_operator< \ operators::name_ \ , T \ > \ inline fn(self_base) \ { \ return 0; \ } template std::string tostring_operator(T const& x) { #ifdef LUABIND_NO_STRINGSTREAM std::strstream s; s << x << std::ends; #else std::stringstream s; s << x; #endif return s.str(); } LUABIND_UNARY_OPERATOR(tostring, tostring_operator, tostring) LUABIND_UNARY_OPERATOR(unm, -, operator-) #undef LUABIND_UNARY_OPERATOR // defined in operator.cpp LUABIND_API extern self_type self; LUABIND_API extern const_self_type const_self; } // namespace luabind #endif // OPERATOR_040729_HPP luabind-1.1.1/luabind/out_value_policy.hpp000066400000000000000000000273751366245310300206620ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED #define LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED #include #include // for LUABIND_DECORATE_TYPE #include // for find_conversion_policy, etc #include // for by_pointer, by_reference, etc #include // for is_nonconst_pointer, is_nonconst_reference, etc #include // for apply_wrap2 #include #include // for if_ #include // for or_ #include // for is_same #include // for operator new namespace luabind { namespace detail { namespace mpl = boost::mpl; template struct char_array { char storage[N]; }; #if defined(__GNUC__) && ( __GNUC__ == 3 && __GNUC_MINOR__ == 1 ) template char_array indirect_sizeof_test(by_reference); template char_array indirect_sizeof_test(by_const_reference); template char_array indirect_sizeof_test(by_pointer); template char_array indirect_sizeof_test(by_const_pointer); template char_array indirect_sizeof_test(by_value); #else template char_array::type)> indirect_sizeof_test(by_reference); template char_array::type)> indirect_sizeof_test(by_const_reference); template char_array::type)> indirect_sizeof_test(by_pointer); template char_array::type)> indirect_sizeof_test(by_const_pointer); template char_array::type)> indirect_sizeof_test(by_value); #endif template struct indirect_sizeof { BOOST_STATIC_CONSTANT(int, value = sizeof(indirect_sizeof_test(LUABIND_DECORATE_TYPE(T)))); }; template struct out_value_converter { int consumed_args() const { return 1; } template T& apply(lua_State* L, by_reference, int index) { typedef typename find_conversion_policy<1, Policies>::type converter_policy; typename mpl::apply_wrap2::type converter; #if defined(__GNUC__) && __GNUC__ >= 4 T* storage = reinterpret_cast(m_storage); new (storage) T(converter.apply(L, LUABIND_DECORATE_TYPE(T), index)); return *storage; #else new (m_storage) T(converter.apply(L, LUABIND_DECORATE_TYPE(T), index)); return *reinterpret_cast(m_storage); #endif } template static int match(lua_State* L, by_reference, int index) { typedef typename find_conversion_policy<1, Policies>::type converter_policy; typedef typename mpl::apply_wrap2::type converter; return converter::match(L, LUABIND_DECORATE_TYPE(T), index); } template void converter_postcall(lua_State* L, by_reference, int) { typedef typename find_conversion_policy<2, Policies>::type converter_policy; typename mpl::apply_wrap2::type converter; #if defined(__GNUC__) && __GNUC__ >= 4 T* storage = reinterpret_cast(m_storage); converter.apply(L, *storage); storage->~T(); #else converter.apply(L, *reinterpret_cast(m_storage)); reinterpret_cast(m_storage)->~T(); #endif } template T* apply(lua_State* L, by_pointer, int index) { typedef typename find_conversion_policy<1, Policies>::type converter_policy; typename mpl::apply_wrap2::type converter; #if defined(__GNUC__) && __GNUC__ >= 4 T* storage = reinterpret_cast(m_storage); new (storage) T(converter.apply(L, LUABIND_DECORATE_TYPE(T), index)); return storage; #else new (m_storage) T(converter.apply(L, LUABIND_DECORATE_TYPE(T), index)); return reinterpret_cast(m_storage); #endif } template static int match(lua_State* L, by_pointer, int index) { typedef typename find_conversion_policy<1, Policies>::type converter_policy; typedef typename mpl::apply_wrap2::type converter; return converter::match(L, LUABIND_DECORATE_TYPE(T), index); } template void converter_postcall(lua_State* L, by_pointer, int) { typedef typename find_conversion_policy<2, Policies>::type converter_policy; typename mpl::apply_wrap2::type converter; #if defined(__GNUC__) && __GNUC__ >= 4 T* storage = reinterpret_cast(m_storage); converter.apply(L, *storage); storage->~T(); #else converter.apply(L, *reinterpret_cast(m_storage)); reinterpret_cast(m_storage)->~T(); #endif } char m_storage[Size]; }; template struct out_value_policy : conversion_policy { static void precall(lua_State*, const index_map&) {} static void postcall(lua_State*, const index_map&) {} struct only_accepts_nonconst_references_or_pointers {}; struct can_only_convert_from_lua_to_cpp {}; template struct apply { typedef typename boost::mpl::if_ , typename boost::mpl::if_, is_nonconst_pointer > , out_value_converter::value, Policies> , only_accepts_nonconst_references_or_pointers >::type , can_only_convert_from_lua_to_cpp >::type type; }; }; template struct pure_out_value_converter { int consumed_args() const { return 0; } template T& apply(lua_State*, by_reference, int) { #if defined(__GNUC__) && __GNUC__ >= 4 T* storage = reinterpret_cast(m_storage); new (storage) T(); return *storage; #else new (m_storage) T(); return *reinterpret_cast(m_storage); #endif } template static int match(lua_State*, by_reference, int) { return 0; } template void converter_postcall(lua_State* L, by_reference, int) { typedef typename find_conversion_policy<1, Policies>::type converter_policy; typename mpl::apply_wrap2::type converter; #if defined(__GNUC__) && __GNUC__ >= 4 T* storage = reinterpret_cast(m_storage); converter.apply(L, *storage); storage->~T(); #else converter.apply(L, *reinterpret_cast(m_storage)); reinterpret_cast(m_storage)->~T(); #endif } template T* apply(lua_State*, by_pointer, int) { #if defined(__GNUC__) && __GNUC__ >= 4 T* storage = reinterpret_cast(m_storage); new (storage) T(); return storage; #else new (m_storage) T(); return reinterpret_cast(m_storage); #endif } template static int match(lua_State*, by_pointer, int) { return 0; } template void converter_postcall(lua_State* L, by_pointer, int) { typedef typename find_conversion_policy<1, Policies>::type converter_policy; typename mpl::apply_wrap2::type converter; #if defined(__GNUC__) && __GNUC__ >= 4 T* storage = reinterpret_cast(m_storage); converter.apply(L, *storage); storage->~T(); #else converter.apply(L, *reinterpret_cast(m_storage)); reinterpret_cast(m_storage)->~T(); #endif } char m_storage[Size]; }; template struct pure_out_value_policy : conversion_policy { static void precall(lua_State*, const index_map&) {} static void postcall(lua_State*, const index_map&) {} struct only_accepts_nonconst_references_or_pointers {}; struct can_only_convert_from_lua_to_cpp {}; template struct apply { typedef typename boost::mpl::if_ , typename boost::mpl::if_, is_nonconst_pointer > , pure_out_value_converter::value, Policies> , only_accepts_nonconst_references_or_pointers >::type , can_only_convert_from_lua_to_cpp >::type type; }; }; }} namespace luabind { template detail::policy_cons, detail::null_type> out_value(LUABIND_PLACEHOLDER_ARG(N)) { return detail::policy_cons, detail::null_type>(); } template detail::policy_cons, detail::null_type> out_value(LUABIND_PLACEHOLDER_ARG(N), const Policies&) { return detail::policy_cons, detail::null_type>(); } template detail::policy_cons, detail::null_type> pure_out_value(LUABIND_PLACEHOLDER_ARG(N)) { return detail::policy_cons, detail::null_type>(); } template detail::policy_cons, detail::null_type> pure_out_value(LUABIND_PLACEHOLDER_ARG(N), const Policies&) { return detail::policy_cons, detail::null_type>(); } } #endif // LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED luabind-1.1.1/luabind/prefix.hpp000066400000000000000000000023611366245310300165610ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin // 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. #ifndef PREFIX_040218_HPP #define PREFIX_040218_HPP #ifdef LUABIND_PREFIX_INCLUDE # include LUABIND_PREFIX_INCLUDE #endif #endif // PREFIX_040218_HPP luabind-1.1.1/luabind/raw_policy.hpp000066400000000000000000000045721366245310300174420ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_RAW_POLICY_HPP_INCLUDED #define LUABIND_RAW_POLICY_HPP_INCLUDED #include #include namespace luabind { namespace detail { struct raw_converter { int consumed_args() const { return 0; } lua_State* apply(lua_State* L, by_pointer, int) { return L; } static int match(...) { return 0; } void converter_postcall(lua_State*, by_pointer, int) {} }; template struct raw_policy : conversion_policy { static void precall(lua_State*, const index_map&) {} static void postcall(lua_State*, const index_map&) {} template struct apply { typedef raw_converter type; }; }; }} // namespace luabind::detail namespace luabind { template detail::policy_cons< detail::raw_policy , detail::null_type > inline raw(LUABIND_PLACEHOLDER_ARG(N)) { return detail::policy_cons< detail::raw_policy , detail::null_type >(); } } // namespace luabind #endif // LUABIND_RAW_POLICY_HPP_INCLUDED luabind-1.1.1/luabind/return_reference_to_policy.hpp000066400000000000000000000051451366245310300227050ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_RETURN_REFERENCE_TO_POLICY_HPP_INCLUDED #define LUABIND_RETURN_REFERENCE_TO_POLICY_HPP_INCLUDED #include // for index_map, policy_cons, etc #include // for lua_State, lua_pushnil, etc namespace luabind { namespace detail { struct cpp_to_lua; struct null_type; template struct return_reference_to_converter; template<> struct return_reference_to_converter { template void apply(lua_State* L, const T&) { lua_pushnil(L); } }; template struct return_reference_to_policy : conversion_policy<0> { static void precall(lua_State*, const index_map&) {} static void postcall(lua_State* L, const index_map& indices) { int result_index = indices[0]; int ref_to_index = indices[N]; lua_pushvalue(L, ref_to_index); lua_replace(L, result_index); } template struct apply { typedef return_reference_to_converter type; }; }; }} namespace luabind { template detail::policy_cons, detail::null_type> return_reference_to(LUABIND_PLACEHOLDER_ARG(N)) { return detail::policy_cons, detail::null_type>(); } } #endif // LUABIND_RETURN_REFERENCE_TO_POLICY_HPP_INCLUDED luabind-1.1.1/luabind/scope.hpp000066400000000000000000000056001366245310300163740ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #ifndef NEW_SCOPE_040211_HPP #define NEW_SCOPE_040211_HPP #include #include #include #include #include namespace luabind { struct scope; } // namespace luabind namespace luabind { namespace detail { struct LUABIND_API registration { registration(); virtual ~registration(); protected: virtual void register_(lua_State*) const = 0; private: friend struct ::luabind::scope; registration* m_next; }; }} // namespace luabind::detail namespace luabind { struct LUABIND_API scope { scope(); #ifdef LUABIND_USE_CXX11 explicit scope(std::unique_ptr reg); #else explicit scope(std::auto_ptr reg); #endif scope(scope const& other_); ~scope(); scope& operator=(scope const& other_); scope& operator,(const scope& s); void register_(lua_State* L) const; private: detail::registration* m_chain; }; class LUABIND_API namespace_ : public scope { public: explicit namespace_(char const* name); namespace_& operator[](scope s); private: struct registration_; registration_* m_registration; }; class LUABIND_API module_ { public: module_(object const& table); module_(lua_State* L, char const* name); void operator[](scope s); private: object m_table; }; inline module_ module(object const& table) { return module_(table); } inline module_ module(lua_State* L, char const* name = 0) { return module_(L, name); } } // namespace luabind #endif // NEW_SCOPE_040211_HPP luabind-1.1.1/luabind/set_package_preload.hpp000066400000000000000000000046241366245310300212440ustar00rootroot00000000000000/** @file @brief Header @date 2012 @author Ryan Pavlik and http://academic.cleardefinition.com/ Iowa State University Virtual Reality Applications Center Human-Computer Interaction Graduate Program */ // Copyright Iowa State University 2012. // 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. #pragma once #ifndef INCLUDED_set_package_preload_hpp_GUID_563c882e_86f7_4ea7_8603_4594ea41737e #define INCLUDED_set_package_preload_hpp_GUID_563c882e_86f7_4ea7_8603_4594ea41737e // Internal Includes #include #include #include // Library/third-party includes #include // Standard includes // - none namespace luabind { LUABIND_API void set_package_preload( lua_State* L, char const* modulename, object const& loader); template void set_package_preload( lua_State* L, char const* modulename, F loader) { object f = make_function(L, loader); // Call add_overload to correctly set the name of f. Inefficiency // should not matter here. detail::add_overload(luabind::newtable(L), modulename, f); set_package_preload(L, modulename, f); } } #endif // INCLUDED_set_package_preload_hpp_GUID_563c882e_86f7_4ea7_8603_4594ea41737e luabind-1.1.1/luabind/shared_ptr_converter.hpp000066400000000000000000000122321366245310300215040ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_SHARED_PTR_CONVERTER_090211_HPP # define LUABIND_SHARED_PTR_CONVERTER_090211_HPP # include // for LUABIND_DECORATE_TYPE # include // for default_converter, etc # include # include // for get_main_thread # include // for handle # include // for bool_, false_ # include // for shared_ptr, get_deleter namespace luabind { namespace mpl = boost::mpl; namespace detail { LUABIND_API extern char state_use_count_tag; struct LUABIND_API shared_ptr_deleter { shared_ptr_deleter(lua_State* L, int index) : life_support(get_main_thread(L), L, index) { alter_use_count(L, +1); } void operator()(void const*) { lua_State* L = life_support.interpreter(); assert(L); handle().swap(life_support); alter_use_count(L, -1); } handle life_support; private: static void alter_use_count(lua_State* L, lua_Integer diff); }; // From http://stackoverflow.com/a/1007175/2128694 // (by Johannes Schaub - litb, "based on a brilliant idea of someone on // usenet") template struct has_shared_from_this_aux { has_shared_from_this_aux(); // not implemented; silence Clang warning private: struct fallback { int shared_from_this; }; // introduce member name struct derived : T, fallback { derived(); // not implemented; silence MSVC warnings C4510 and C4610 }; template struct check; template static no_t f( check*); template static yes_t f(...); public: BOOST_STATIC_CONSTANT(bool, value = sizeof(f(0)) == sizeof(yes_t)); }; template struct has_shared_from_this: mpl::bool_::value> {}; } // namespace detail using boost::get_deleter; namespace detail { template struct shared_ptr_converter : default_converter { private: typedef P ptr_t; typedef typename ptr_t::element_type* rawptr_t; detail::value_converter m_val_cv; int m_val_score; // no shared_from_this() available ptr_t shared_from_raw(rawptr_t raw, lua_State* L, int index, mpl::false_) { return ptr_t(raw, detail::shared_ptr_deleter(L, index)); } // shared_from_this() available. ptr_t shared_from_raw(rawptr_t raw, lua_State*, int, mpl::true_) { return ptr_t(raw->shared_from_this(), raw); } public: shared_ptr_converter(): m_val_score(-1) {} typedef mpl::false_ is_native; template int match(lua_State* L, U, int index) { // Check if the value on the stack is a holder with exactly ptr_t // as pointer type. m_val_score = m_val_cv.match(L, LUABIND_DECORATE_TYPE(ptr_t), index); if (m_val_score >= 0) return m_val_score; // Fall back to raw_ptr. return default_converter::match( L, LUABIND_DECORATE_TYPE(rawptr_t), index); } template ptr_t apply(lua_State* L, U, int index) { // First, check if we got away without upcasting. if (m_val_score >= 0) { ptr_t ptr = m_val_cv.apply( L, LUABIND_DECORATE_TYPE(ptr_t), index); return ptr; } // If not obtain, a raw pointer and construct are shared one from it. rawptr_t raw_ptr = default_converter::apply( L, LUABIND_DECORATE_TYPE(rawptr_t), index); if (!raw_ptr) return ptr_t(); return shared_from_raw( raw_ptr, L, index, detail::has_shared_from_this()); } void apply(lua_State* L, ptr_t const& p) { if (detail::shared_ptr_deleter* d = get_deleter(p)) // Rely on ADL. { d->life_support.push(L); } else { m_val_cv.apply(L, p); } } template void converter_postcall(lua_State*, U const&, int) {} }; } // namepace detail template struct default_converter >: detail::shared_ptr_converter > {}; template struct default_converter const&>: detail::shared_ptr_converter > {}; typedef void(*state_unreferenced_fun)(lua_State*); LUABIND_API void set_state_unreferenced_callback( lua_State* L, state_unreferenced_fun cb); LUABIND_API state_unreferenced_fun get_state_unreferenced_callback( lua_State* L); LUABIND_API bool is_state_unreferenced(lua_State* L); } // namespace luabind #endif // LUABIND_SHARED_PTR_CONVERTER_090211_HPP luabind-1.1.1/luabind/stack.hpp000066400000000000000000000076601366245310300164000ustar00rootroot00000000000000#ifndef LUABIND_STACK_HPP_INCLUDED #define LUABIND_STACK_HPP_INCLUDED #include #include #include #include #include #include #include #include namespace luabind { namespace detail { namespace mpl = boost::mpl; template void push_aux(lua_State* L, T& value, ConverterGenerator*) { typedef typename boost::mpl::if_< boost::is_reference_wrapper , BOOST_DEDUCED_TYPENAME boost::unwrap_reference::type& , T >::type unwrapped_type; typename mpl::apply_wrap2< ConverterGenerator,unwrapped_type,cpp_to_lua >::type cv; cv.apply( L , boost::implicit_cast< BOOST_DEDUCED_TYPENAME boost::unwrap_reference::type& >(value) ); } } // namespace detail template void push(lua_State* L, T& value, Policies const&) { typedef typename detail::find_conversion_policy< 0 , Policies >::type converter_policy; push_aux(L, value, static_cast(0)); } template void push(lua_State* L, T& value) { push(L, value, detail::null_type()); } namespace detail { template< class T , class Policies , class ErrorPolicy , class ReturnType > ReturnType from_lua_aux( lua_State* L , int idx , T* , Policies* , ErrorPolicy* , ReturnType* ) { #ifndef LUABIND_NO_ERROR_CHECKING if (!L) return ErrorPolicy::handle_error(L, typeid(void)); #endif typedef typename detail::find_conversion_policy< 0 , Policies >::type converter_generator; typename mpl::apply_wrap2::type cv; if (cv.match(L, LUABIND_DECORATE_TYPE(T), idx) < 0) { return ErrorPolicy::handle_error(L, typeid(T)); } return cv.apply(L, LUABIND_DECORATE_TYPE(T), idx); } # ifdef BOOST_MSVC # pragma warning(push) # pragma warning(disable:4702) // unreachable code # endif template struct throw_error_policy { static T handle_error(lua_State* L, type_id const& type_info) { #ifndef LUABIND_NO_EXCEPTIONS throw cast_failed(L, type_info); #else cast_failed_callback_fun e = get_cast_failed_callback(); if (e) e(L, type_info); assert(0 && "object_cast failed. If you want to handle this error use " "luabind::set_error_callback()"); std::terminate(); return *(typename boost::remove_reference::type*)0; #endif } }; # ifdef BOOST_MSVC # pragma warning(pop) # endif template struct nothrow_error_policy { static boost::optional handle_error(lua_State*, type_id const&) { return boost::optional(); } }; } // namespace detail template T from_lua(lua_State* L, int idx, Policies const&) { return detail::from_lua_aux( L , idx , static_cast(0) , static_cast(0) , static_cast*>(0) , static_cast(0) ); } template T from_lua(lua_State* L, int idx) { return from_lua(L, idx, detail::null_type()); } template boost::optional from_lua_nothrow(lua_State* L, int idx, Policies const&) { return detail::from_lua_aux( L , idx , static_cast(0) , static_cast(0) , static_cast*>(0) , static_cast*>(0) ); } template boost::optional from_lua_nothrow(lua_State* L, int idx) { return from_lua_nothrow(L, idx, detail::null_type()); } } // namespace luabind #endif // LUABIND_STACK_HPP_INCLUDED luabind-1.1.1/luabind/std_shared_ptr_converter.hpp000066400000000000000000000043371366245310300223650ustar00rootroot00000000000000// Copyright Christian Neumüller 2012. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_STD_SHAREDPTR_CONVERTER_HPP_INCLUDED #define LUABIND_STD_SHAREDPTR_CONVERTER_HPP_INCLUDED LUABIND_STD_SHAREDPTR_CONVERTER_HPP_INCLUDED #include #if defined(LUABIND_NO_STD_SHARED_PTR) \ || defined(BOOST_NO_CXX11_SMART_PTR) \ && !defined(BOOST_HAS_TR1_SHARED_PTR) \ && (!defined(BOOST_MSVC) || BOOST_MSVC < 1600) # ifndef LUABIND_NO_STD_SHARED_PTR # define LUABIND_NO_STD_SHARED_PTR # endif #else # include # include // shared_ptr # if BOOST_VERSION >= 105300 # include # include namespace luabind { namespace detail { namespace has_get_pointer_ { template struct impl> { BOOST_STATIC_CONSTANT(bool, value = true); typedef boost::mpl::bool_ type; }; template struct impl>: impl> { }; template struct impl>: impl> { }; template struct impl>: impl> { }; }} using boost::get_pointer; } # else // if BOOST_VERSION < 105300 // Not standard conforming: add function to ::std(::tr1) namespace std { # if defined(_MSC_VER) && _MSC_VER < 1700 namespace tr1 { # endif template T * get_pointer(shared_ptr const& p) { return p.get(); } # if defined(_MSC_VER) && _MSC_VER < 1700 } // namespace tr1 # endif } // namespace std #endif // if BOOST_VERSION < 105300 / else namespace luabind { using std::get_deleter; template struct default_converter >: detail::shared_ptr_converter > {}; template struct default_converter const&>: detail::shared_ptr_converter > {}; } // namespace luabind #endif // if smart pointers are available #endif // LUABIND_STD_SHAREDPTR_CONVERTER_HPP_INCLUDED luabind-1.1.1/luabind/tag_function.hpp000066400000000000000000000031261366245310300177440ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_TAG_FUNCTION_081129_HPP # define LUABIND_TAG_FUNCTION_081129_HPP # include # if LUABIND_MAX_ARITY <= 8 # include # else # include # endif # include # include # include # include # include namespace luabind { namespace detail { struct invoke_context; struct function_object; template struct tagged_function { tagged_function(F f_) : f(f_) {} F f; }; template struct signature_aux > { typedef Signature type; }; template int invoke( lua_State* L, function_object const& self, invoke_context& ctx , tagged_function const& tagged , SignatureSeq, Policies const& policies) { return invoke(L, self, ctx, tagged.f, SignatureSeq(), policies); } } // namespace detail template detail::tagged_function tag_function(F f) { return f; } } // namespace luabind #endif // LUABIND_TAG_FUNCTION_081129_HPP luabind-1.1.1/luabind/typeid.hpp000066400000000000000000000047021366245310300165630ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_TYPEID_081227_HPP # define LUABIND_TYPEID_081227_HPP # include # include # include # include # include # include // boost/units/detail/utility.hpp # if defined(__GLIBCXX__) || defined(__GLIBCPP__) # define LUABIND_USE_DEMANGLING # include # endif // __GNUC__ // See https://svn.boost.org/trac/boost/ticket/754 # if (defined(__GNUC__) && __GNUC__ >= 3) \ || defined(_AIX) \ || (defined(__sgi) && defined(__host_mips)) \ || (defined(__hpux) && defined(__HP_aCC)) \ || (defined(linux) && defined(__INTEL_COMPILER) && defined(__ICC)) # define LUABIND_SAFE_TYPEID # endif namespace luabind { # ifdef BOOST_MSVC # pragma warning(push) // std::type_info::before() returns int, rather than bool. // At least on MSVC7.1, this is true for the comparison // operators as well. # pragma warning(disable:4800) # endif class type_id : boost::less_than_comparable { public: type_id() : m_id(&typeid(detail::null_type)) {} type_id(std::type_info const& id) : m_id(&id) {} bool operator!=(type_id const& other) const { # ifdef LUABIND_SAFE_TYPEID return std::strcmp(m_id->name(), other.m_id->name()) != 0; # else return *m_id != *other.m_id; # endif } bool operator==(type_id const& other) const { # ifdef LUABIND_SAFE_TYPEID return std::strcmp(m_id->name(), other.m_id->name()) == 0; # else return *m_id == *other.m_id; # endif } bool operator<(type_id const& other) const { # ifdef LUABIND_SAFE_TYPEID return std::strcmp(m_id->name(), other.m_id->name()) < 0; # else return m_id->before(*other.m_id); # endif } std::string name() const { # ifdef LUABIND_USE_DEMANGLING int status; char* buf = abi::__cxa_demangle(m_id->name(), 0, 0, &status); if (buf != 0) { std::string demangled_name(buf); std::free(buf); return demangled_name; } # endif return m_id->name(); } private: std::type_info const* m_id; }; # ifdef BOOST_MSVC # pragma warning(pop) # endif } // namespace luabind #endif // LUABIND_TYPEID_081227_HPP luabind-1.1.1/luabind/value_wrapper.hpp000066400000000000000000000102211366245310300201320ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_VALUE_WRAPPER_050419_HPP #define LUABIND_VALUE_WRAPPER_050419_HPP #include #include #include #ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION # define LUABIND_USE_VALUE_WRAPPER_TAG #else #endif #ifdef LUABIND_USE_VALUE_WRAPPER_TAG # include # include # include # include # include # include # include # include # include #endif namespace luabind { // // Concept ``ValueWrapper`` // #ifdef LUABIND_USE_VALUE_WRAPPER_TAG template struct value_wrapper_traits; namespace detail { BOOST_MPL_HAS_XXX_TRAIT_DEF(value_wrapper_tag); struct unspecialized_value_wrapper_traits { typedef boost::mpl::false_ is_specialized; }; template struct value_wrapper_traits_aux { typedef value_wrapper_traits type; }; } // namespace detail #endif template struct value_wrapper_traits #ifdef LUABIND_USE_VALUE_WRAPPER_TAG : boost::mpl::eval_if< boost::mpl::and_< boost::mpl::not_< boost::mpl::or_< boost::is_reference , boost::is_pointer , boost::is_array > > , detail::has_value_wrapper_tag > , detail::value_wrapper_traits_aux , boost::mpl::identity >::type {}; #else { typedef boost::mpl::false_ is_specialized; }; #endif template struct is_value_wrapper : boost::mpl::aux::msvc_eti_base< typename value_wrapper_traits::is_specialized >::type {}; } // namespace luabind #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION # include # include namespace luabind { template struct is_value_wrapper_arg : is_value_wrapper< typename boost::remove_const< typename boost::remove_reference::type >::type > {}; } // namespace luabind #else # include # include namespace luabind { namespace detail { template typename is_value_wrapper::type is_value_wrapper_arg_check(T const*); yes_t to_yesno(boost::mpl::true_); no_t to_yesno(boost::mpl::false_); template struct is_value_wrapper_arg_aux { static typename boost::add_reference::type x; BOOST_STATIC_CONSTANT(bool, value = sizeof(to_yesno(is_value_wrapper_arg_check(&x))) == sizeof(yes_t) ); typedef boost::mpl::bool_ type; }; } // namespace detail template struct is_value_wrapper_arg : detail::is_value_wrapper_arg_aux::type { }; } // namespace luabind #endif #endif // LUABIND_VALUE_WRAPPER_050419_HPP luabind-1.1.1/luabind/version.hpp000066400000000000000000000010011366245310300167370ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef LUABIND_VERSION_090216_HPP # define LUABIND_VERSION_090216_HPP # define LUABIND_VERSION 900 // Each component uses two digits, so: // // major = LUABIND_VERSION / 10000 // minor = LUABIND_VERSION / 100 % 100 // patch = LUABIND_VERSION % 100 #endif // LUABIND_VERSION_090216_HPP luabind-1.1.1/luabind/weak_ref.hpp000066400000000000000000000034521366245310300170510ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #ifndef WEAK_REF_040402_HPP #define WEAK_REF_040402_HPP #include #include namespace luabind { class LUABIND_API weak_ref { public: weak_ref(); weak_ref(lua_State* main, lua_State* L, int index); weak_ref(weak_ref const&); ~weak_ref(); weak_ref& operator=(weak_ref const&); void swap(weak_ref&); // returns a unique id that no // other weak ref will return int id() const; lua_State* state() const; void get(lua_State* L) const; private: struct impl; impl* m_impl; }; } // namespace luabind #endif // WEAK_REF_040402_HPP luabind-1.1.1/luabind/wrapper_base.hpp000066400000000000000000000135431366245310300177420ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #if !BOOST_PP_IS_ITERATING #ifndef LUABIND_WRAPPER_BASE_HPP_INCLUDED #define LUABIND_WRAPPER_BASE_HPP_INCLUDED #include #include #include #include #include #include #include namespace luabind { namespace detail { struct wrap_access; } struct wrapped_self_t: weak_ref { handle m_strong_ref; }; struct wrap_base { friend struct detail::wrap_access; wrap_base() {} #define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LUABIND_MAX_ARITY, , 1)) #include BOOST_PP_ITERATE() private: wrapped_self_t m_self; }; #define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LUABIND_MAX_ARITY, , 2)) #include BOOST_PP_ITERATE() namespace detail { struct wrap_access { static wrapped_self_t const& ref(wrap_base const& b) { return b.m_self; } static wrapped_self_t& ref(wrap_base& b) { return b.m_self; } }; } } #endif // LUABIND_WRAPPER_BASE_HPP_INCLUDED #else #if BOOST_PP_ITERATION_FLAGS() == 1 #define LUABIND_TUPLE_PARAMS(z, n, data) const A##n * #define LUABIND_OPERATOR_PARAMS(z, n, data) const A##n & a##n template typename boost::mpl::if_ , luabind::detail::proxy_member_void_caller > , luabind::detail::proxy_member_caller > >::type call(char const* name BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _), detail::type_* = 0) const { typedef boost::tuples::tuple tuple_t; #if BOOST_PP_ITERATION() == 0 tuple_t args; #else tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a)); #endif typedef typename boost::mpl::if_ , luabind::detail::proxy_member_void_caller > , luabind::detail::proxy_member_caller > >::type proxy_type; // this will be cleaned up by the proxy object // once the call has been made // TODO: what happens if this virtual function is // dispatched from a lua thread where the state // pointer is different? // get the function lua_State* L = m_self.state(); m_self.get(L); assert(!lua_isnil(L, -1)); detail::do_call_member_selection(L, name); if (lua_isnil(L, -1)) { lua_pop(L, 1); throw std::runtime_error("Attempt to call nonexistent function"); } // push the self reference as the first parameter m_self.get(L); // now the function and self objects // are on the stack. These will both // be popped by pcall return proxy_type(L, args); } #undef LUABIND_CALL_MEMBER_NAME #undef LUABIND_OPERATOR_PARAMS #undef LUABIND_TUPLE_PARAMS #else // free call_member forwardarding functions #define N BOOST_PP_ITERATION() #define LUABIND_TUPLE_PARAMS(z, n, data) const A##n * #define LUABIND_OPERATOR_PARAMS(z, n, data) const A##n & a##n template< class R BOOST_PP_ENUM_TRAILING_PARAMS(N, class A) > typename boost::mpl::if_< boost::is_void , detail::proxy_member_void_caller< boost::tuples::tuple< BOOST_PP_ENUM(N, LUABIND_TUPLE_PARAMS, _) > > , detail::proxy_member_caller< R , boost::tuples::tuple< BOOST_PP_ENUM(N, LUABIND_TUPLE_PARAMS, _) > > >::type call_member( wrap_base const* self , char const* fn BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(N, A, &a) , detail::type_* = 0 ) { return self->call( fn BOOST_PP_ENUM_TRAILING_PARAMS(N, a) , (detail::type_*)0 ); } #undef LUABIND_OPERATOR_PARAMS #undef LUABIND_TUPLE_PARAMS #undef N #endif #endif luabind-1.1.1/luabind/yield_policy.hpp000066400000000000000000000033061366245310300177510ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_YIELD_POLICY_HPP_INCLUDED #define LUABIND_YIELD_POLICY_HPP_INCLUDED #include #include namespace luabind { namespace detail { struct yield_policy { static void precall(lua_State*, const index_map&) {} static void postcall(lua_State*, const index_map&) {} }; }} namespace luabind { detail::policy_cons const yield = {}; namespace detail { inline void ignore_unused_yield() { (void)yield; } } } #endif // LUABIND_YIELD_POLICY_HPP_INCLUDED luabind-1.1.1/src/000077500000000000000000000000001366245310300137225ustar00rootroot00000000000000luabind-1.1.1/src/CMakeLists.txt000066400000000000000000000125651366245310300164730ustar00rootroot00000000000000# Build for LuaBind # Ryan Pavlik # http://academic.cleardefinition.com/ # Iowa State University HCI Graduate Program/VRAC # ls *.cpp | sort | sed "s/^/ /" set(LUABIND_SRCS class.cpp class_info.cpp class_registry.cpp class_rep.cpp create_class.cpp error.cpp exception_handler.cpp function.cpp function_introspection.cpp inheritance.cpp link_compatibility.cpp lua51compat.cpp object_rep.cpp open.cpp operator.cpp pcall.cpp scope.cpp set_package_preload.cpp shared_ptr_converter.cpp stack_content_by_name.cpp weak_ref.cpp wrapper_base.cpp) # ls ../luabind/*.hpp | sort | sed "s/^/ /" set(LUABIND_API ../luabind/adopt_policy.hpp ../luabind/back_reference_fwd.hpp ../luabind/back_reference.hpp ../luabind/class.hpp ../luabind/class_info.hpp ../luabind/config.hpp ../luabind/container_policy.hpp ../luabind/copy_policy.hpp ../luabind/dependency_policy.hpp ../luabind/discard_result_policy.hpp ../luabind/error_callback_fun.hpp ../luabind/error.hpp ../luabind/exception_handler.hpp ../luabind/from_stack.hpp ../luabind/function_converter.hpp ../luabind/function.hpp ../luabind/function_introspection.hpp ../luabind/get_main_thread.hpp ../luabind/get_pointer.hpp ../luabind/handle.hpp ../luabind/intrusive_ptr_converter.hpp ../luabind/iterator_policy.hpp ../luabind/luabind.hpp ../luabind/lua_include.hpp ../luabind/lua_state_fwd.hpp ../luabind/make_function.hpp ../luabind/nil.hpp ../luabind/no_dependency.hpp ../luabind/object_fwd.hpp ../luabind/object.hpp ../luabind/open.hpp ../luabind/operator.hpp ../luabind/out_value_policy.hpp ../luabind/prefix.hpp ../luabind/raw_policy.hpp ../luabind/return_reference_to_policy.hpp ../luabind/scope.hpp ../luabind/set_package_preload.hpp ../luabind/shared_ptr_converter.hpp ../luabind/stack.hpp ../luabind/std_shared_ptr_converter.hpp ../luabind/tag_function.hpp ../luabind/typeid.hpp ../luabind/value_wrapper.hpp ../luabind/version.hpp ../luabind/weak_ref.hpp ../luabind/wrapper_base.hpp ../luabind/yield_policy.hpp) source_group(API FILES ${LUABIND_API}) # ls ../luabind/detail/*.hpp | sort | sed "s/^/ /" set(LUABIND_DETAIL_API ../luabind/detail/call_function.hpp ../luabind/detail/call.hpp ../luabind/detail/call_member.hpp ../luabind/detail/call_operator_iterate.hpp ../luabind/detail/class_registry.hpp ../luabind/detail/class_rep.hpp ../luabind/detail/constructor.hpp ../luabind/detail/convert_to_lua.hpp ../luabind/detail/debug.hpp ../luabind/detail/decorate_type.hpp ../luabind/detail/deduce_signature.hpp ../luabind/detail/enum_maker.hpp ../luabind/detail/format_signature.hpp ../luabind/detail/garbage_collector.hpp ../luabind/detail/has_get_pointer.hpp ../luabind/detail/inheritance.hpp ../luabind/detail/instance_holder.hpp ../luabind/detail/link_compatibility.hpp ../luabind/detail/make_instance.hpp ../luabind/detail/most_derived.hpp ../luabind/detail/object_call.hpp ../luabind/detail/object.hpp ../luabind/detail/object_rep.hpp ../luabind/detail/operator_id.hpp ../luabind/detail/other.hpp ../luabind/detail/pcall.hpp ../luabind/detail/pointee_sizeof.hpp ../luabind/detail/policy.hpp ../luabind/detail/primitives.hpp ../luabind/detail/property.hpp ../luabind/detail/signature_match.hpp ../luabind/detail/stack_utils.hpp ../luabind/detail/typetraits.hpp ../luabind/detail/yes_no.hpp) source_group(Internal FILES ${LUABIND_DETAIL_API}) set(LUABIND_EXTRA_LIBS) if(MSVC) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4251") elseif(CMAKE_COMPILER_IS_GNUCXX) # TODO we often need libm, not just with gcc. list(APPEND LUABIND_EXTRA_LIBS m) endif() set(CMAKE_DEBUG_POSTFIX "-d") add_library(luabind ${LUABIND_SRCS} ${LUABIND_API} ${LUABIND_DETAIL_API}) target_link_libraries(luabind ${LUA_LIBRARIES} ${LUABIND_EXTRA_LIBS} ${CMAKE_DL_LIBS}) set_property(TARGET luabind PROPERTY COMPILE_FLAGS ${CMAKE_SHARED_LIBRARY_C_FLAGS}) set_property(TARGET luabind PROPERTY PROJECT_LABEL "LuaBind Library") if (LUABIND_APPEND_VERSION_SUFFIX) set_property(TARGET luabind PROPERTY OUTPUT_NAME "luabind09") else() # This is neccesary when the LUABIND_APPEND_VERSION_SUFFIX variable is # changed from ON to OFF. set_property(TARGET luabind PROPERTY OUTPUT_NAME "luabind") endif() set(ALLHEADERS ${LUABIND_API} ${LUABIND_DETAIL_API} PARENT_SCOPE) set(APIHEADERS ${LUABIND_API} PARENT_SCOPE) if(LUABIND_INSTALL) if(NOT INCLUDE_DIR) set(INCLUDE_DIR include) endif() if(NOT LIB_DIR) set(LIB_DIR lib) endif() if(NOT ARCH_DIR) set(ARCH_DIR lib) endif() if(NOT BIN_DIR) set(BIN_DIR bin) endif() install(FILES ${LUABIND_API} DESTINATION ${INCLUDE_DIR}/luabind COMPONENT sdk) install(FILES ${LUABIND_DETAIL_API} DESTINATION ${INCLUDE_DIR}/luabind/detail COMPONENT sdk) install(TARGETS luabind EXPORT luabind RUNTIME DESTINATION ${BIN_DIR} COMPONENT runtime LIBRARY DESTINATION ${LIB_DIR} COMPONENT runtime ARCHIVE DESTINATION ${ARCH_DIR} COMPONENT sdk) endif() luabind-1.1.1/src/class.cpp000066400000000000000000000223011366245310300155310ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include #include #include #include #include #include #include namespace luabind { LUABIND_API detail::nil_type nil; } namespace luabind { namespace detail { namespace { struct cast_entry { cast_entry(class_id src_, class_id target_, cast_function cast_) : src(src_) , target(target_) , cast(cast_) {} class_id src; class_id target; cast_function cast; }; } // namespace unnamed struct class_registration : registration { class_registration(char const* name); void register_(lua_State* L) const; const char* m_name; mutable std::map m_static_constants; mutable std::vector m_bases; type_id m_type; class_id m_id; class_id m_wrapper_id; type_id m_wrapper_type; std::vector m_casts; scope m_scope; scope m_members; scope m_default_members; }; class_registration::class_registration(char const* name) { m_name = name; } void class_registration::register_(lua_State* L) const { LUABIND_CHECK_STACK(L); assert(lua_type(L, -1) == LUA_TTABLE); if (m_name != 0) { lua_pushstring(L, m_name); } detail::class_rep* crep; detail::class_registry* r = detail::class_registry::get_registry(L); // create a class_rep structure for this class. // allocate it within lua to let lua collect it on // lua_close(). This is better than allocating it // as a static, since it will then be destructed // when the program exits instead. // warning: we assume that lua will not // move the userdata memory. lua_newuserdata(L, sizeof(detail::class_rep)); crep = reinterpret_cast(lua_touserdata(L, -1)); new(crep) detail::class_rep( m_type , m_name , L ); // register this new type in the class registry r->add_class(m_type, crep); lua_rawgetp(L, LUA_REGISTRYINDEX, &class_map_tag); class_map& classes = *static_cast( lua_touserdata(L, -1)); lua_pop(L, 1); classes.put(m_id, crep); bool const has_wrapper = m_wrapper_id != registered_class::id; if (has_wrapper) classes.put(m_wrapper_id, crep); crep->m_static_constants.swap(m_static_constants); detail::class_registry* registry = detail::class_registry::get_registry(L); crep->get_default_table(L); m_scope.register_(L); m_default_members.register_(L); lua_pop(L, 1); crep->get_table(L); m_members.register_(L); lua_pop(L, 1); lua_rawgetp(L, LUA_REGISTRYINDEX, &cast_graph_tag); cast_graph* const casts = static_cast( lua_touserdata(L, -1)); lua_pop(L, 1); lua_rawgetp(L, LUA_REGISTRYINDEX, &classid_map_tag); class_id_map* const class_ids = static_cast( lua_touserdata(L, -1)); lua_pop(L, 1); class_ids->put(m_id, m_type); if (has_wrapper) class_ids->put(m_wrapper_id, m_wrapper_type); BOOST_FOREACH(cast_entry const& e, m_casts) { casts->insert(e.src, e.target, e.cast); } for (std::vector::iterator i = m_bases.begin(); i != m_bases.end(); ++i) { LUABIND_CHECK_STACK(L); // the baseclass' class_rep structure detail::class_rep* bcrep = registry->find_class(*i); crep->add_base_class(bcrep); // copy base class table crep->get_table(L); bcrep->get_table(L); lua_pushnil(L); while (lua_next(L, -2)) { lua_pushvalue(L, -2); // copy key lua_gettable(L, -5); if (!lua_isnil(L, -1)) { lua_pop(L, 2); continue; } lua_pop(L, 1); lua_pushvalue(L, -2); // copy key lua_insert(L, -2); lua_settable(L, -5); } lua_pop(L, 2); // copy base class detaults table crep->get_default_table(L); bcrep->get_default_table(L); lua_pushnil(L); while (lua_next(L, -2)) { lua_pushvalue(L, -2); // copy key lua_gettable(L, -5); if (!lua_isnil(L, -1)) { lua_pop(L, 2); continue; } lua_pop(L, 1); lua_pushvalue(L, -2); // copy key lua_insert(L, -2); lua_settable(L, -5); } lua_pop(L, 2); } if (m_name != 0) { lua_settable(L, -3); } else { lua_pop(L, 1); } } // -- interface --------------------------------------------------------- class_base::class_base(char const* name_) #ifdef LUABIND_USE_CXX11 : scope(std::unique_ptr( #else : scope(std::auto_ptr( #endif m_registration = new class_registration(name_)) ) { } void class_base::init( type_id const& type_id_, class_id id , type_id const& wrapper_type, class_id wrapper_id) { m_registration->m_type = type_id_; m_registration->m_id = id; m_registration->m_wrapper_type = wrapper_type; m_registration->m_wrapper_id = wrapper_id; } void class_base::add_base(type_id const& base) { m_registration->m_bases.push_back(base); } void class_base::add_member(registration* member) { #ifdef LUABIND_USE_CXX11 std::unique_ptr ptr(member); m_registration->m_members.operator,(scope(std::move(ptr))); #else std::auto_ptr ptr(member); m_registration->m_members.operator,(scope(ptr)); #endif } void class_base::add_default_member(registration* member) { #ifdef LUABIND_USE_CXX11 std::unique_ptr ptr(member); m_registration->m_default_members.operator,(scope(std::move(ptr))); #else std::auto_ptr ptr(member); m_registration->m_default_members.operator,(scope(ptr)); #endif } const char* class_base::name() const { return m_registration->m_name; } void class_base::add_static_constant(const char* name_, int val) { m_registration->m_static_constants[name_] = val; } void class_base::add_inner_scope(scope& s) { m_registration->m_scope.operator,(s); } void class_base::add_cast( class_id src, class_id target, cast_function cast) { m_registration->m_casts.push_back(cast_entry(src, target, cast)); } std::string get_class_name(lua_State* L, type_id const& i) { std::string ret; assert(L); class_registry* r = class_registry::get_registry(L); class_rep* crep = r->find_class(i); if (!crep || !crep->name()) { ret = crep ? "unnamed [" : "custom ["; ret += i.name(); ret += ']'; } else { /* TODO reimplement this? if (i == crep->holder_type()) { ret += "smart_ptr<"; ret += crep->name(); ret += ">"; } else if (i == crep->const_holder_type()) { ret += "smart_ptrname(); ret += ">"; } else*/ { ret += crep->name(); } } return ret; } }} // namespace luabind::detail luabind-1.1.1/src/class_info.cpp000066400000000000000000000106631366245310300165540ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include #include #include #include /* #include #define VERBOSE(X) std::cout << __FILE__ << ":" << __LINE__ << ": " << X << std::endl */ #define VERBOSE(X) namespace luabind { LUABIND_API class_info get_class_info(argument const& o) { lua_State* L = o.interpreter(); detail::class_rep * crep = NULL; o.push(L); if (detail::is_class_rep(L, -1)) { VERBOSE("OK, got a class rep"); // OK, o is a class rep, now at the top of the stack crep = static_cast(lua_touserdata(L, -1)); lua_pop(L, 1); } else { VERBOSE("Not a class rep"); detail::object_rep* obj = detail::get_instance(L, -1); if (!obj) { VERBOSE("Not a obj rep"); class_info result; result.name = lua_typename(L, lua_type(L, -1)); lua_pop(L, 1); result.methods = newtable(L); result.attributes = newtable(L); return result; } else { lua_pop(L, 1); // OK, we were given an object - gotta get the crep. crep = obj->crep(); } } crep->get_table(L); object table(from_stack(L, -1)); lua_pop(L, 1); class_info result; result.name = detail::get_class_name(L, crep->type()); result.methods = newtable(L); result.attributes = newtable(L); std::size_t index = 1; for (iterator i(table), e; i != e; ++i) { if (type(*i) != LUA_TFUNCTION) continue; // We have to create a temporary `object` here, otherwise the proxy // returned by operator->() will mess up the stack. This is a known // problem that probably doesn't show up in real code very often. object member(*i); member.push(L); detail::stack_pop pop(L, 1); if (lua_tocfunction(L, -1) == &detail::property_tag) { result.attributes[index++] = i.key(); } else { result.methods[i.key()] = *i; } } return result; } LUABIND_API object get_class_names(lua_State* L) { detail::class_registry* reg = detail::class_registry::get_registry(L); std::map const& classes = reg->get_classes(); object result = newtable(L); std::size_t index = 1; for (std::map::const_iterator iter = classes.begin(); iter != classes.end(); ++iter) { result[index++] = iter->second->name(); } return result; } LUABIND_API void bind_class_info(lua_State* L) { module(L) [ class_("class_info_data") .def_readonly("name", &class_info::name) .def_readonly("methods", &class_info::methods) .def_readonly("attributes", &class_info::attributes), def("class_info", &get_class_info), def("class_names", &get_class_names) ]; } } luabind-1.1.1/src/class_registry.cpp000066400000000000000000000115231366245310300174650ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin // 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. #define LUABIND_BUILDING #include // for LUABIND_API #include // for class_registry #include // for class_rep #include // for garbage_collector #include // for push_instance_metatable #include // for type_id #include // for lua_pushstring, lua_rawset, etc #include // for assert #include // for map, etc #include // for pair namespace luabind { namespace detail { char classes_tag = 0; namespace { int create_cpp_class_metatable(lua_State* L) { lua_createtable(L, 0, 7); // mark the table with our unique tag // that says that the user data that has this // metatable is a class_rep lua_pushboolean(L, true); lua_rawsetp(L, -2, &classrep_tag); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, &garbage_collector); lua_rawset(L, -3); lua_pushliteral(L, "__call"); lua_pushcfunction(L, &class_rep::constructor_dispatcher); lua_rawset(L, -3); lua_pushliteral(L, "__index"); lua_pushcfunction(L, &class_rep::static_class_gettable); lua_rawset(L, -3); lua_pushliteral(L, "__newindex"); lua_pushcfunction(L, &class_rep::lua_settable_dispatcher); lua_rawset(L, -3); lua_pushliteral(L, "__tostring"); lua_pushcfunction(L, &class_rep::tostring); lua_rawset(L, -3); // Direct calls to metamethods cannot be allowed, because the // callee trusts the caller to pass arguments of the right type. lua_pushliteral(L, "__metatable"); lua_pushboolean(L, true); lua_rawset(L, -3); return luaL_ref(L, LUA_REGISTRYINDEX); } int create_lua_class_metatable(lua_State* L) { return create_cpp_class_metatable(L); } } // namespace unnamed class class_rep; class_registry::class_registry(lua_State* L) : m_cpp_class_metatable(create_cpp_class_metatable(L)) , m_lua_class_metatable(create_lua_class_metatable(L)) { push_instance_metatable(L); m_instance_metatable = luaL_ref(L, LUA_REGISTRYINDEX); } class_registry* class_registry::get_registry(lua_State* L) { #ifdef LUABIND_NOT_THREADSAFE // if we don't have to be thread safe, we can keep a // chache of the class_registry pointer without the // need of a mutex static lua_State* cache_key = 0; static class_registry* registry_cache = 0; if (cache_key == L) return registry_cache; #endif lua_rawgetp(L, LUA_REGISTRYINDEX, &classes_tag); class_registry* p = static_cast(lua_touserdata(L, -1)); lua_pop(L, 1); #ifdef LUABIND_NOT_THREADSAFE cache_key = L; registry_cache = p; #endif return p; } void class_registry::add_class(type_id const& info, class_rep* crep) { // class is already registered assert((m_classes.find(info) == m_classes.end()) && "you are trying to register a class twice"); m_classes[info] = crep; } class_rep* class_registry::find_class(type_id const& info) const { std::map::const_iterator i( m_classes.find(info)); if (i == m_classes.end()) return 0; // the type is not registered return i->second; } }} // namespace luabind::detail luabind-1.1.1/src/class_rep.cpp000066400000000000000000000221171366245310300164040ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include #include #include #include #include #include using namespace luabind::detail; namespace luabind { namespace detail { LUABIND_API int property_tag(lua_State* L) { lua_pushliteral(L, "luabind: property_tag function can't be called"); lua_error(L); return 0; } char classrep_tag = 0; }} luabind::detail::class_rep::class_rep(type_id const& type_ , const char* name_ , lua_State* L ) : m_type(type_) , m_name(name_) , m_class_type(cpp_class) { shared_init(L); } void luabind::detail::class_rep::shared_init(lua_State * L) { lua_newtable(L); handle(L, -1).swap(m_table); lua_newtable(L); handle(L, -1).swap(m_default_table); lua_pop(L, 2); class_registry* r = class_registry::get_registry(L); // the following line should be equivalent whether or not this is a cpp class assert((r->cpp_class() != LUA_NOREF) && "you must call luabind::open()"); lua_rawgeti(L, LUA_REGISTRYINDEX, (m_class_type == cpp_class) ? r->cpp_class() : r->lua_class()); lua_setmetatable(L, -2); handle(L, -1).swap(m_self_ref); m_instance_metatable = (m_class_type == cpp_class) ? r->cpp_instance() : r->lua_instance(); lua_rawgetp(L, LUA_REGISTRYINDEX, &cast_graph_tag); m_casts = static_cast(lua_touserdata(L, -1)); lua_pop(L, 1); lua_rawgetp(L, LUA_REGISTRYINDEX, &classid_map_tag); m_classes = static_cast(lua_touserdata(L, -1)); lua_pop(L, 1); } luabind::detail::class_rep::class_rep(lua_State* L, const char* name_) : m_type(typeid(null_type)) , m_name(name_) , m_class_type(lua_class) { shared_init(L); } luabind::detail::class_rep::~class_rep() { } // leaves object on lua stack std::pair luabind::detail::class_rep::allocate(lua_State* L) const { const int size = sizeof(object_rep); char* mem = static_cast(lua_newuserdata(L, size)); return std::pair(mem, static_cast(0)); } namespace { bool super_deprecation_disabled = false; } // namespace unnamed // this is called as metamethod __call on the class_rep. int luabind::detail::class_rep::constructor_dispatcher(lua_State* L) { class_rep* cls = static_cast(lua_touserdata(L, 1)); int args = lua_gettop(L); push_new_instance(L, cls); if (super_deprecation_disabled && cls->get_class_type() == class_rep::lua_class && !cls->bases().empty()) { lua_pushvalue(L, 1); lua_pushvalue(L, -2); lua_pushcclosure(L, super_callback, 2); lua_setglobal(L, "super"); } lua_pushvalue(L, -1); lua_replace(L, 1); cls->get_table(L); lua_pushliteral(L, "__init"); lua_gettable(L, -2); lua_insert(L, 1); lua_pop(L, 1); lua_insert(L, 1); lua_call(L, args, 0); if (super_deprecation_disabled) { lua_pushnil(L); lua_setglobal(L, "super"); } return 1; } void luabind::detail::class_rep::add_base_class(luabind::detail::class_rep* bcrep) { // If you hit this assert you are deriving from a type that is not registered // in lua. That is, in the class_<> you are giving a baseclass that isn't registered. // Please note that if you don't need to have access to the base class or the // conversion from the derived class to the base class, you don't need // to tell luabind that it derives. assert(bcrep && "You cannot derive from an unregistered type"); // import all static constants for (std::map::const_iterator i = bcrep->m_static_constants.begin(); i != bcrep->m_static_constants.end(); ++i) { int& v = m_static_constants[i->first]; v = i->second; } // also, save the baseclass info to be used for typecasts m_bases.push_back(bcrep); } LUABIND_API void luabind::disable_super_deprecation() { super_deprecation_disabled = true; } int luabind::detail::class_rep::super_callback(lua_State* L) { int args = lua_gettop(L); class_rep* crep = static_cast(lua_touserdata(L, lua_upvalueindex(1))); class_rep* base = crep->bases()[0]; if (base->bases().empty()) { lua_pushnil(L); lua_setglobal(L, "super"); } else { lua_pushlightuserdata(L, base); lua_pushvalue(L, lua_upvalueindex(2)); lua_pushcclosure(L, super_callback, 2); lua_setglobal(L, "super"); } base->get_table(L); lua_pushliteral(L, "__init"); lua_gettable(L, -2); lua_insert(L, 1); lua_pop(L, 1); lua_pushvalue(L, lua_upvalueindex(2)); lua_insert(L, 2); lua_call(L, args + 1, 0); // TODO: instead of clearing the global variable "super" // store it temporarily in the registry. maybe we should // have some kind of warning if the super global is used? lua_pushnil(L); lua_setglobal(L, "super"); return 0; } int luabind::detail::class_rep::lua_settable_dispatcher(lua_State* L) { class_rep* crep = static_cast(lua_touserdata(L, 1)); // get first table crep->get_table(L); // copy key, value lua_pushvalue(L, -3); lua_pushvalue(L, -3); lua_rawset(L, -3); // pop table lua_pop(L, 1); // get default table crep->get_default_table(L); lua_replace(L, 1); lua_rawset(L, -3); return 0; } /* stack: 1: class_rep 2: member name */ int luabind::detail::class_rep::static_class_gettable(lua_State* L) { class_rep* crep = static_cast(lua_touserdata(L, 1)); // look in the static function table crep->get_default_table(L); lua_pushvalue(L, 2); lua_gettable(L, -2); if (!lua_isnil(L, -1)) return 1; else lua_pop(L, 2); const char* key = lua_tostring(L, 2); if (!key) { #ifndef LUABIND_NO_ERROR_CHECKING lua_pushfstring(L, "no static value at %s-index in class '%s'", luaL_typename(L, 2), crep->name()); return lua_error(L); #else lua_pushnil(L); return 1; #endif } if (std::strlen(key) != lua_rawlen(L, 2)) { #ifndef LUABIND_NO_ERROR_CHECKING lua_pushfstring(L, "no static '%s' (followed by embedded 0) in class '%s'", key, crep->name()); return lua_error(L); #else lua_pushnil(L); return 1; #endif } std::map::const_iterator j = crep->m_static_constants.find(key); if (j != crep->m_static_constants.end()) { lua_pushnumber(L, j->second); return 1; } #ifndef LUABIND_NO_ERROR_CHECKING lua_pushfstring(L, "no static '%s' in class '%s'", key, crep->name()); return lua_error(L); #else lua_pushnil(L); return 1; #endif } int luabind::detail::class_rep::tostring(lua_State* L) { class_rep* crep = static_cast(lua_touserdata(L, 1)); lua_pushfstring(L, "class %s", crep->m_name ? crep->m_name : ""); if (crep->m_type != type_id()) { lua_pushfstring(L, " (%s)", crep->m_type.name().c_str()); lua_concat(L, 2); } return 1; } bool luabind::detail::is_class_rep(lua_State* L, int index) { if (!lua_getmetatable(L, index)) return false; lua_rawgetp(L, -1, &classrep_tag); detail::stack_pop pop(L, 2); return !lua_isnil(L, -1); } void luabind::detail::finalize(lua_State* L, class_rep* crep) { if (crep->get_class_type() != class_rep::lua_class) return; // lua_pushvalue(L, -1); // copy the object ref crep->get_table(L); lua_pushliteral(L, "__finalize"); lua_gettable(L, -2); lua_remove(L, -2); if (lua_isnil(L, -1)) { lua_pop(L, 1); } else { lua_pushvalue(L, -2); lua_call(L, 1, 0); } for (std::vector::const_iterator i = crep->bases().begin(); i != crep->bases().end(); ++i) { if (*i) finalize(L, *i); } } luabind-1.1.1/src/create_class.cpp000066400000000000000000000076041366245310300170650ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include #include namespace luabind { namespace detail { namespace { // expects two tables on the lua stack: // 1: destination // 2: source void copy_member_table(lua_State* L) { lua_pushnil(L); while (lua_next(L, -2)) { lua_pushliteral(L, "__init"); if (lua_compare(L, -1, -3, LUA_OPEQ)) { lua_pop(L, 2); continue; } else lua_pop(L, 1); // __init string lua_pushliteral(L, "__finalize"); if (lua_compare(L, -1, -3, LUA_OPEQ)) { lua_pop(L, 2); continue; } else lua_pop(L, 1); // __finalize string lua_pushvalue(L, -2); // copy key lua_insert(L, -2); lua_settable(L, -5); } } } int create_class::stage2(lua_State* L) { class_rep* crep = static_cast(lua_touserdata(L, lua_upvalueindex(1))); assert((crep != 0) && "internal error, please report"); assert((is_class_rep(L, lua_upvalueindex(1))) && "internal error, please report"); #ifndef LUABIND_NO_ERROR_CHECKING if (!is_class_rep(L, 1)) { lua_pushliteral(L, "expected class to derive from or a newline"); lua_error(L); } #endif class_rep* base = static_cast(lua_touserdata(L, 1)); crep->add_base_class(base); // copy base class members crep->get_table(L); base->get_table(L); copy_member_table(L); crep->get_default_table(L); base->get_default_table(L); copy_member_table(L); crep->set_type(base->type()); return 0; } int create_class::stage1(lua_State* L) { #ifndef LUABIND_NO_ERROR_CHECKING if (lua_gettop(L) != 1 || lua_type(L, 1) != LUA_TSTRING || lua_isnumber(L, 1)) { lua_pushliteral(L, "invalid construct, expected class name"); lua_error(L); } if (std::strlen(lua_tostring(L, 1)) != lua_rawlen(L, 1)) { lua_pushliteral(L, "luabind does not support class names with extra nulls"); lua_error(L); } #endif const char* name = lua_tostring(L, 1); void* c = lua_newuserdata(L, sizeof(class_rep)); new(c) class_rep(L, name); // make the class globally available lua_pushvalue(L, -1); lua_setglobal(L, name); // also add it to the closure as return value lua_pushcclosure(L, &stage2, 1); return 1; } }} luabind-1.1.1/src/error.cpp000066400000000000000000000037661366245310300155730ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include namespace luabind { namespace { pcall_callback_fun pcall_callback = 0; #ifdef LUABIND_NO_EXCEPTIONS error_callback_fun error_callback = 0; cast_failed_callback_fun cast_failed_callback = 0; #endif } #ifdef LUABIND_NO_EXCEPTIONS void set_error_callback(error_callback_fun e) { error_callback = e; } void set_cast_failed_callback(cast_failed_callback_fun c) { cast_failed_callback = c; } error_callback_fun get_error_callback() { return error_callback; } cast_failed_callback_fun get_cast_failed_callback() { return cast_failed_callback; } #endif void set_pcall_callback(pcall_callback_fun e) { pcall_callback = e; } pcall_callback_fun get_pcall_callback() { return pcall_callback; } } luabind-1.1.1/src/exception_handler.cpp000066400000000000000000000042101366245310300201160ustar00rootroot00000000000000// Copyright Daniel Wallin 2005. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #define LUABIND_BUILDING #include // for LUABIND_API #ifndef LUABIND_NO_EXCEPTIONS #include // for error #include // for exception_handler_base #include #include // for exception #include // for logic_error, runtime_error namespace luabind { namespace detail { namespace { exception_handler_base* handler_chain = 0; void push_exception_string(lua_State* L, char const* exception, char const* what) { lua_pushstring(L, exception); lua_pushliteral(L, ": '"); lua_pushstring(L, what); lua_pushliteral(L, "'"); lua_concat(L, 4); } } void exception_handler_base::try_next(lua_State* L) const { if (next) next->handle(L); else throw; } LUABIND_API void handle_exception_aux(lua_State* L) { try { if (handler_chain) handler_chain->handle(L); else throw; } catch (error const&) {} catch (std::logic_error const& e) { push_exception_string(L, "std::logic_error", e.what()); } catch (std::runtime_error const& e) { push_exception_string(L, "std::runtime_error", e.what()); } catch (std::exception const& e) { push_exception_string(L, "std::exception", e.what()); } catch (char const* str) { push_exception_string(L, "c-string", str); } catch (...) { lua_pushliteral(L, "Unknown C++ exception"); } } LUABIND_API void register_exception_handler(exception_handler_base* handler) { if (!handler_chain) handler_chain = handler; else { exception_handler_base* p = handler_chain; for (; p->next; p = p->next); handler->next = 0; p->next = handler; } } }} // namespace luabind::detail #endif // LUABIND_NO_EXCEPTIONS luabind-1.1.1/src/function.cpp000066400000000000000000000071461366245310300162630ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #define LUABIND_BUILDING #include namespace luabind { namespace detail { namespace { // A pointer to this is used as a tag value to identify functions exported // by luabind. char function_tag = 0; int function_destroy(lua_State* L) { function_object* fn = *static_cast( lua_touserdata(L, 1)); delete fn; return 0; } void push_function_metatable(lua_State* L) { lua_rawgetp(L, LUA_REGISTRYINDEX, &function_tag); if (lua_istable(L, -1)) return; lua_pop(L, 1); lua_createtable(L, 0, 1); // One non-sequence entry for __gc. lua_pushliteral(L, "__gc"); lua_pushcfunction(L, &function_destroy); lua_rawset(L, -3); lua_pushvalue(L, -1); lua_rawsetp(L, LUA_REGISTRYINDEX, &function_tag); } } // namespace unnamed LUABIND_API bool is_luabind_function(lua_State* L, int index) { if (!lua_getupvalue(L, index, 2)) return false; bool result = lua_touserdata(L, -1) == &function_tag; lua_pop(L, 1); return result; } namespace { inline bool is_luabind_function(object const& obj) { obj.push(obj.interpreter()); bool result = detail::is_luabind_function(obj.interpreter(), -1); lua_pop(obj.interpreter(), 1); return result; } } // namespace unnamed LUABIND_API void add_overload( object const& context, char const* name, object const& fn) { function_object* f = *touserdata(getupvalue(fn, 1)); f->name = name; if (object overloads = context[name]) { if (is_luabind_function(overloads) && is_luabind_function(fn)) { f->next = *touserdata(getupvalue(overloads, 1)); f->keepalive = overloads; } } context[name] = fn; } LUABIND_API object make_function_aux(lua_State* L, function_object* impl) { void* storage = lua_newuserdata(L, sizeof(function_object*)); push_function_metatable(L); *static_cast(storage) = impl; lua_setmetatable(L, -2); lua_pushlightuserdata(L, &function_tag); lua_pushcclosure(L, impl->entry, 2); stack_pop pop(L, 1); return object(from_stack(L, -1)); } void invoke_context::format_error( lua_State* L, function_object const* overloads) const { char const* function_name = overloads->name.empty() ? "" : overloads->name.c_str(); if (candidate_index == 0) { lua_pushliteral(L, "No matching overload found, candidates:"); for (function_object const* f = overloads; f != 0; f = f->next) { lua_pushliteral(L, "\n"); f->format_signature(L, function_name); lua_concat(L, 3); // Inefficient, but does not use up the stack. } } else { // Ambiguous lua_pushliteral(L, "Ambiguous, candidates:"); for (int i = 0; i < candidate_index; ++i) { lua_pushliteral(L, "\n"); candidates[i]->format_signature(L, function_name); lua_concat(L, 3); // Inefficient, but does not use up the stack. } if (additional_candidates) { BOOST_ASSERT(candidate_index == max_candidates); lua_pushfstring(L, "\nand %d additional overload(s) not shown", additional_candidates); lua_concat(L, 2); } } } }} // namespace luabind::detail luabind-1.1.1/src/function_introspection.cpp000066400000000000000000000071641366245310300212430ustar00rootroot00000000000000/** @file @brief Implementation @date 2012 @author Ryan Pavlik and http://academic.cleardefinition.com/ Iowa State University Virtual Reality Applications Center Human-Computer Interaction Graduate Program */ // Copyright Iowa State University 2012. // 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. #define LUABIND_BUILDING // Internal Includes #include // for LUABIND_API #include // for function_object #include // for stack_pop #include // for from_stack #include // for def, is_luabind_function #include #include // for argument, object, etc #include // for module, module_, scope // Library/third-party includes // - none // Standard includes #include // for string #include // for NULL namespace luabind { namespace { detail::function_object* get_function_object(argument const& fn) { lua_State * L = fn.interpreter(); { fn.push(L); detail::stack_pop pop(L, 1); if (!detail::is_luabind_function(L, -1)) { return NULL; } } return *touserdata(getupvalue(fn, 1)); } std::string get_function_name(argument const& fn) { detail::function_object * f = get_function_object(fn); if (!f) { return ""; } return f->name; } object get_function_overloads(argument const& fn) { lua_State * L = fn.interpreter(); detail::function_object * fobj = get_function_object(fn); if (!fobj) { return object(); } object overloadTable(newtable(L)); int count = 1; const char * function_name = fobj->name.c_str(); for (detail::function_object const* f = fobj; f != 0; f = f->next) { f->format_signature(L, function_name); detail::stack_pop pop(L, 1); overloadTable[count] = object(from_stack(L, -1)); ++count; } /// @todo return overloadTable; } } LUABIND_API int bind_function_introspection(lua_State * L) { module(L, "function_info")[ def("get_function_overloads", &get_function_overloads), def("get_function_name", &get_function_name) ]; return 0; } } // end of namespace luabind luabind-1.1.1/src/inheritance.cpp000066400000000000000000000146041366245310300167240ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #define LUABIND_BUILDING #include #include #include #include #include #include #include #include #include #include namespace luabind { namespace detail { LUABIND_API char classid_map_tag = 0; LUABIND_API char class_map_tag = 0; char cast_graph_tag = 0; class_id const class_id_map::local_id_base = std::numeric_limits::max() / 2; namespace { struct edge { edge(class_id target_, cast_function cast_) : target(target_) , cast(cast_) {} class_id target; cast_function cast; }; bool operator<(edge const& x, edge const& y) { return x.target < y.target; } struct vertex { vertex(class_id id_) : id(id_) {} class_id id; std::vector edges; }; typedef std::pair cache_entry; class cache { public: static std::ptrdiff_t const unknown; static std::ptrdiff_t const invalid; cache_entry get( class_id src, class_id target, class_id dynamic_id , std::ptrdiff_t object_offset) const; void put( class_id src, class_id target, class_id dynamic_id , std::ptrdiff_t object_offset , std::ptrdiff_t offset, int distance); void invalidate(); private: typedef boost::tuple< class_id, class_id, class_id, std::ptrdiff_t> key_type; typedef std::map map_type; map_type m_cache; }; std::ptrdiff_t const cache::unknown = std::numeric_limits::max(); std::ptrdiff_t const cache::invalid = cache::unknown - 1; cache_entry cache::get( class_id src, class_id target, class_id dynamic_id , std::ptrdiff_t object_offset) const { map_type::const_iterator i = m_cache.find( key_type(src, target, dynamic_id, object_offset)); return i != m_cache.end() ? i->second : cache_entry(unknown, -1); } void cache::put( class_id src, class_id target, class_id dynamic_id , std::ptrdiff_t object_offset, std::ptrdiff_t offset, int distance) { m_cache.insert(std::make_pair( key_type(src, target, dynamic_id, object_offset) , cache_entry(offset, distance) )); } void cache::invalidate() { m_cache.clear(); } } // namespace unnamed class cast_graph::impl { public: std::pair cast( void* p, class_id src, class_id target , class_id dynamic_id, void const* dynamic_ptr) const; void insert(class_id src, class_id target, cast_function cast); private: std::vector m_vertices; mutable cache m_cache; }; namespace { struct queue_entry { queue_entry(void* p_, class_id vertex_id_, int distance_) : p(p_) , vertex_id(vertex_id_) , distance(distance_) {} void* p; class_id vertex_id; int distance; }; } // namespace unnamed std::pair cast_graph::impl::cast( void* const p, class_id src, class_id target , class_id dynamic_id, void const* dynamic_ptr) const { if (src == target) return std::make_pair(p, 0); if (src >= m_vertices.size() || target >= m_vertices.size()) return std::pair(static_cast(0), -1); std::ptrdiff_t const object_offset = static_cast(dynamic_ptr) - static_cast(p); cache_entry cached = m_cache.get(src, target, dynamic_id, object_offset); if (cached.first != cache::unknown) { if (cached.first == cache::invalid) return std::pair(static_cast(0), -1); return std::make_pair(static_cast(p) + cached.first, cached.second); } std::queue q; q.push(queue_entry(p, src, 0)); boost::dynamic_bitset<> visited(m_vertices.size()); while (!q.empty()) { queue_entry const qe = q.front(); q.pop(); visited[qe.vertex_id] = true; vertex const& v = m_vertices[qe.vertex_id]; if (v.id == target) { m_cache.put( src, target, dynamic_id, object_offset , static_cast(qe.p) - static_cast(p), qe.distance ); return std::make_pair(qe.p, qe.distance); } BOOST_FOREACH(edge const& e, v.edges) { if (visited[e.target]) continue; if (void* casted = e.cast(qe.p)) q.push(queue_entry(casted, e.target, qe.distance + 1)); } } m_cache.put(src, target, dynamic_id, object_offset, cache::invalid, -1); return std::pair(static_cast(0), -1); } void cast_graph::impl::insert( class_id src, class_id target, cast_function cast_) { class_id const max_id = std::max(src, target); if (max_id >= m_vertices.size()) { m_vertices.reserve(max_id + 1); for (class_id i = m_vertices.size(); i < max_id + 1; ++i) m_vertices.push_back(vertex(i)); } std::vector& edges = m_vertices[src].edges; std::vector::iterator i = std::lower_bound( edges.begin(), edges.end(), edge(target, 0) ); if (i == edges.end() || i->target != target) { edges.insert(i, edge(target, cast_)); m_cache.invalidate(); } } std::pair cast_graph::cast( void* p, class_id src, class_id target , class_id dynamic_id, void const* dynamic_ptr) const { return m_impl->cast(p, src, target, dynamic_id, dynamic_ptr); } void cast_graph::insert(class_id src, class_id target, cast_function cast_) { m_impl->insert(src, target, cast_); } cast_graph::cast_graph() : m_impl(new impl) {} cast_graph::~cast_graph() {} LUABIND_API class_id allocate_class_id(type_id const& cls) { typedef std::map map_type; static map_type registered; static class_id id = 0; std::pair inserted = registered.insert( std::make_pair(cls, id)); if (inserted.second) ++id; return inserted.first->second; } }} // namespace luabind::detail luabind-1.1.1/src/link_compatibility.cpp000066400000000000000000000030021366245310300203070ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include namespace luabind { namespace detail { #ifdef LUABIND_NOT_THREADSAFE void not_threadsafe_defined_conflict() {} #else void not_threadsafe_not_defined_conflict() {} #endif #ifdef LUABIND_NO_ERROR_CHECKING void no_error_checking_defined_conflict() {} #else void no_error_checking_not_defined_conflict() {} #endif }} luabind-1.1.1/src/lua51compat.cpp000066400000000000000000000043531366245310300165660ustar00rootroot00000000000000// Copyright Christian Neumller 2015. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #define LUABIND_BUILDING #include #if LUA_VERSION_NUM < 502 // Taken (with slightly adapted formatting) from Lua 5.2.3: /* ** $Id: lauxlib.c,v 1.248.1.1 2013/04/12 18:48:47 roberto Exp $ ** Auxiliary functions for building Lua libraries * Copyright (C) 1994-2013 Lua.org, PUC-Rio. * * 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. */ LUABIND_API char const* luaL_tolstring (lua_State* L, int idx, size_t* len) { if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */ switch (lua_type(L, idx)) { case LUA_TNUMBER: case LUA_TSTRING: lua_pushvalue(L, idx); break; case LUA_TBOOLEAN: lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false")); break; case LUA_TNIL: lua_pushliteral(L, "nil"); break; default: lua_pushfstring(L, "%s: %p", luaL_typename(L, idx), lua_topointer(L, idx)); break; } } return lua_tolstring(L, -1, len); } #endif // LUA_VERSION_NUM < 502 luabind-1.1.1/src/object_rep.cpp000066400000000000000000000240041366245310300165420ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include #include // for get_class_name #include #include #include namespace luabind { namespace detail { // dest is a function that is called to delete the c++ object this struct holds object_rep::object_rep(instance_holder* instance, class_rep* crep_) : m_instance(instance) , m_classrep(crep_) , m_dependency_cnt(0) {} object_rep::~object_rep() { if (!m_instance) return; m_instance->~instance_holder(); deallocate(m_instance); } void object_rep::add_dependency(lua_State* L, int index) { assert(m_dependency_cnt < sizeof(object_rep)); void* key = reinterpret_cast(this) + m_dependency_cnt; lua_pushlightuserdata(L, key); lua_pushvalue(L, index); lua_rawset(L, LUA_REGISTRYINDEX); ++m_dependency_cnt; } void object_rep::release_dependency_refs(lua_State* L) { for (std::size_t i = 0; i < m_dependency_cnt; ++i) { void* key = reinterpret_cast(this) + i; lua_pushlightuserdata(L, key); lua_pushnil(L); lua_rawset(L, LUA_REGISTRYINDEX); } } static int destroy_instance(lua_State* L) { object_rep* instance = static_cast(lua_touserdata(L, 1)); lua_pushliteral(L, "__finalize"); lua_gettable(L, 1); if (lua_isnil(L, -1)) { lua_pop(L, 1); } else { lua_pushvalue(L, 1); lua_call(L, 1, 0); } instance->release_dependency_refs(L); instance->~object_rep(); lua_pushnil(L); lua_setmetatable(L, 1); return 0; } namespace { int set_instance_value(lua_State* L) { lua_getuservalue(L, 1); lua_pushvalue(L, 2); lua_rawget(L, -2); if (lua_isnil(L, -1) && lua_getmetatable(L, -2)) { lua_pushvalue(L, 2); lua_rawget(L, -2); lua_replace(L, -3); lua_pop(L, 1); } if (lua_tocfunction(L, -1) == &property_tag && lua_tocfunction(L, 3) != &property_tag) { // this member is a property, extract the "set" function and call it. lua_getupvalue(L, -1, 2); if (lua_isnil(L, -1)) { lua_pushfstring(L, "property '%s' is read only", lua_tostring(L, 2)); lua_error(L); } lua_pushvalue(L, 1); lua_pushvalue(L, 3); lua_call(L, 2, 0); return 0; } lua_pop(L, 1); if (!lua_getmetatable(L, 4)) { lua_newtable(L); lua_pushvalue(L, -1); lua_setuservalue(L, 1); lua_pushvalue(L, 4); lua_setmetatable(L, -2); } else { lua_pop(L, 1); } lua_pushvalue(L, 2); lua_pushvalue(L, 3); lua_rawset(L, -3); return 0; } int get_instance_value(lua_State* L) { lua_getuservalue(L, 1); lua_pushvalue(L, 2); lua_rawget(L, -2); if (lua_isnil(L, -1) && lua_getmetatable(L, -2)) { lua_pushvalue(L, 2); lua_rawget(L, -2); } if (lua_tocfunction(L, -1) == &property_tag) { // this member is a property, extract the "get" function and call it. lua_getupvalue(L, -1, 1); lua_pushvalue(L, 1); lua_call(L, 1, 1); } return 1; } int dispatch_operator(lua_State* L) { int const name_upvalue = lua_upvalueindex(1); for (int i = 0; i < 2; ++i) { if (get_instance(L, 1 + i)) { int nargs = lua_gettop(L); lua_pushvalue(L, name_upvalue); // operator name // instance[operator name] (via get_instance_value / __index) lua_gettable(L, 1 + i); if (lua_isnil(L, -1)) { lua_pop(L, 1); continue; } lua_insert(L, 1); // move the function to the bottom bool const is_unary = lua_toboolean(L, lua_upvalueindex(2)) ? true : false; // Avoid MSVC "performance warning". nargs = is_unary ? 1 : nargs; if (is_unary) // remove trailing nil lua_remove(L, 3); lua_call(L, nargs, LUA_MULTRET); return lua_gettop(L); } } object_rep* inst = get_instance(L, 1); assert(inst); char const* op_name = lua_tostring(L, name_upvalue); if (std::strcmp(op_name, "__eq") == 0) { object_rep* inst2 = get_instance(L, 2); if (!inst2) { lua_pushboolean(L, false); return 1; } class_id clsid = inst->crep()->classes().get( inst->crep()->type()); void* addr = inst->get_instance(clsid).first; void* addr2 = inst2->get_instance(clsid).first; bool const null_inst = !addr; if (!addr2) { clsid = inst2->crep()->classes().get( inst2->crep()->type()); addr = inst->get_instance(clsid).first; addr2 = inst2->get_instance(clsid).first; if (!addr2) { lua_pushboolean(L, null_inst); return 1; } } lua_pushboolean(L, addr == addr2); return 1; } char const* const_s = inst->is_const() ? "const " : ""; std::string const cls_name = get_class_name(L, inst->crep()->type()); if (std::strcmp(op_name, "__tostring") == 0) { class_id clsid = inst->crep()->classes().get( inst->crep()->type()); void* addr = inst->get_instance(clsid).first; lua_pushfstring(L, "%s%s object: %p", const_s, cls_name.c_str(), addr); return 1; } lua_pushfstring(L, "%sclass %s: no %s operator defined.", const_s, cls_name.c_str(), op_name); return lua_error(L); } } // namespace unnamed LUABIND_API void push_instance_metatable(lua_State* L) { // One sequence entry for the tag, 4 non-sequence entries for // __gc, __index, __newindex and __metatable and // one more for each operator. lua_createtable(L, 1, 4 + number_of_operators); // This is used as a tag to determine if a userdata is a luabind // instance. We use a numeric key and a cclosure for fast comparision. lua_pushcfunction(L, get_instance_value); lua_rawseti(L, -2, 1); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, destroy_instance); lua_rawset(L, -3); lua_pushliteral(L, "__index"); lua_pushcfunction(L, get_instance_value); lua_rawset(L, -3); lua_pushliteral(L, "__newindex"); lua_pushcfunction(L, set_instance_value); lua_rawset(L, -3); // Direct calls to metamethods cannot be allowed, because the // callee trusts the caller to pass arguments of the right type. lua_pushliteral(L, "__metatable"); lua_pushboolean(L, true); lua_rawset(L, -3); for (int op = 0; op < number_of_operators; ++op) { lua_pushstring(L, get_operator_name(op)); lua_pushvalue(L, -1); lua_pushboolean(L, op == op_unm || op == op_len); // Unary? lua_pushcclosure(L, &dispatch_operator, 2); lua_rawset(L, -3); } } LUABIND_API object_rep* get_instance(lua_State* L, int index) { object_rep* result = static_cast(lua_touserdata(L, index)); if (!result || !lua_getmetatable(L, index)) return 0; lua_rawgeti(L, -1, 1); if (lua_tocfunction(L, -1) != &get_instance_value) result = 0; lua_pop(L, 2); return result; } LUABIND_API object_rep* push_new_instance(lua_State* L, class_rep* cls) { void* storage = lua_newuserdata(L, sizeof(object_rep)); object_rep* result = new (storage) object_rep(0, cls); cls->get_table(L); lua_setuservalue(L, -2); lua_rawgeti(L, LUA_REGISTRYINDEX, cls->metatable_ref()); lua_setmetatable(L, -2); return result; } }} luabind-1.1.1/src/open.cpp000066400000000000000000000107101366245310300153660ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include #include #include #include #include namespace luabind { namespace { int make_property(lua_State* L) { int args = lua_gettop(L); if (args == 0 || args > 2) { lua_pushliteral(L, "make_property() called with wrong number of arguments."); lua_error(L); } if (args == 1) lua_pushnil(L); lua_pushcclosure(L, &detail::property_tag, 2); return 1; } int main_thread_tag; int deprecated_super(lua_State* L) { lua_pushliteral(L, "DEPRECATION: 'super' has been deprecated in favor of " "directly calling the base class __init() function. " "This error can be disabled by calling 'luabind::disable_super_deprecation()'." ); lua_error(L); return 0; } } // namespace unnamed LUABIND_API lua_State* get_main_thread(lua_State* L) { lua_pushlightuserdata(L, &main_thread_tag); lua_rawget(L, LUA_REGISTRYINDEX); lua_State* result = static_cast(lua_touserdata(L, -1)); lua_pop(L, 1); if (!result) throw std::runtime_error("Unable to get main thread, luabind::open() not called?"); return result; } namespace { template inline void* create_gc_udata(lua_State* L, void* tag) { void* storage = lua_newuserdata(L, sizeof(T)); // set gc metatable lua_createtable(L, 0, 1); // one (non-sequence) element. lua_pushcfunction(L, &detail::garbage_collector); lua_setfield(L, -2, "__gc"); lua_setmetatable(L, -2); lua_rawsetp(L, LUA_REGISTRYINDEX, tag); return storage; } template inline void push_gc_udata(lua_State* L, void* tag) { void* storage = create_gc_udata(L, tag); new (storage) T; } template inline void push_gc_udata(lua_State* L, void* tag, A1 constructorArg) { void* storage = create_gc_udata(L, tag); new (storage) T(constructorArg); } } LUABIND_API void open(lua_State* L) { bool is_main_thread = lua_pushthread(L) == 1; lua_pop(L, 1); if (!is_main_thread) { throw std::runtime_error( "luabind::open() must be called with the main thread " "lua_State*" ); } push_gc_udata(L, &detail::classes_tag, L); push_gc_udata(L, &detail::classid_map_tag); push_gc_udata(L, &detail::cast_graph_tag); push_gc_udata(L, &detail::class_map_tag); // add functions (class, cast etc...) lua_pushcfunction(L, detail::create_class::stage1); lua_setglobal(L, "class"); lua_pushcfunction(L, &make_property); lua_setglobal(L, "property"); lua_pushlightuserdata(L, &main_thread_tag); lua_pushlightuserdata(L, L); lua_rawset(L, LUA_REGISTRYINDEX); lua_pushcfunction(L, &deprecated_super); lua_setglobal(L, "super"); } } // namespace luabind luabind-1.1.1/src/operator.cpp000066400000000000000000000024051366245310300162620ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include namespace luabind { LUABIND_API self_type self; LUABIND_API const_self_type const_self; } luabind-1.1.1/src/pcall.cpp000066400000000000000000000042161366245310300155240ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include #include #include namespace luabind { namespace detail { int pcall(lua_State *L, int nargs, int nresults) { pcall_callback_fun e = get_pcall_callback(); int en = 0; if ( e ) { int base = lua_gettop(L) - nargs; lua_pushcfunction(L, e); lua_insert(L, base); // push pcall_callback under chunk and args en = base; } int result = lua_pcall(L, nargs, nresults, en); if ( en ) lua_remove(L, en); // remove pcall_callback return result; } int resume_impl(lua_State *L, int nargs, int) { #if LUA_VERSION_NUM >= 502 int res = lua_resume(L, NULL, nargs); #else int res = lua_resume(L, nargs); #endif // Lua 5.1 added LUA_YIELD as a possible return value, // this was causing crashes, because the caller expects 0 on success. return (res == LUA_YIELD) ? 0 : res; } }} luabind-1.1.1/src/scope.cpp000066400000000000000000000120411366245310300155350ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include #include #include #include #include namespace luabind { namespace detail { registration::registration() : m_next(0) { } registration::~registration() { delete m_next; } } // namespace detail scope::scope() : m_chain(0) { } #ifdef LUABIND_USE_CXX11 scope::scope(std::unique_ptr reg) #else scope::scope(std::auto_ptr reg) #endif : m_chain(reg.release()) { } scope::scope(scope const& other) : m_chain(other.m_chain) { const_cast(other).m_chain = 0; } scope& scope::operator=(scope const& other_) { delete m_chain; m_chain = other_.m_chain; const_cast(other_).m_chain = 0; return *this; } scope::~scope() { delete m_chain; } scope& scope::operator,(const scope& s) { if (!m_chain) { m_chain = s.m_chain; const_cast(s).m_chain = 0; return *this; } for (detail::registration* c = m_chain;; c = c->m_next) { if (!c->m_next) { c->m_next = s.m_chain; const_cast(s).m_chain = 0; break; } } return *this; } void scope::register_(lua_State* L) const { for (detail::registration* r = m_chain; r != 0; r = r->m_next) { LUABIND_CHECK_STACK(L); r->register_(L); } } } // namespace luabind namespace luabind { namespace { struct lua_pop_stack { lua_pop_stack(lua_State* L) : m_state(L) { } ~lua_pop_stack() { lua_pop(m_state, 1); } lua_State* m_state; }; } // namespace unnamed module_::module_(object const& table) : m_table(table) { } module_::module_(lua_State* L, char const* name) { if (name) { lua_getglobal(L, name); if (!lua_istable(L, -1)) { lua_pop(L, 1); lua_newtable(L); lua_pushvalue(L, -1); lua_setglobal(L, name); } } else { lua_pushglobaltable(L); } m_table = object(from_stack(L, -1)); lua_pop(L, 1); } void module_::operator[](scope s) { lua_State* L = m_table.interpreter(); m_table.push(L); lua_pop_stack guard(L); s.register_(L); } struct namespace_::registration_ : detail::registration { registration_(char const* name) : m_name(name) { } void register_(lua_State* L) const { LUABIND_CHECK_STACK(L); assert(lua_gettop(L) >= 1); lua_pushstring(L, m_name); lua_gettable(L, -2); detail::stack_pop p(L, 1); // pops the table on exit if (!lua_istable(L, -1)) { lua_pop(L, 1); lua_newtable(L); lua_pushstring(L, m_name); lua_pushvalue(L, -2); lua_settable(L, -4); } m_scope.register_(L); } char const* m_name; scope m_scope; }; namespace_::namespace_(char const* name) #ifdef LUABIND_USE_CXX11 : scope(std::unique_ptr( #else : scope(std::auto_ptr( #endif m_registration = new registration_(name))) { } namespace_& namespace_::operator[](scope s) { m_registration->m_scope.operator,(s); return *this; } } // namespace luabind luabind-1.1.1/src/set_package_preload.cpp000066400000000000000000000061741366245310300204120ustar00rootroot00000000000000/** @file @brief Implementation @date 2012 @author Ryan Pavlik and http://academic.cleardefinition.com/ Iowa State University Virtual Reality Applications Center Human-Computer Interaction Graduate Program */ // Copyright Iowa State University 2012. // 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. #define LUABIND_BUILDING // Internal Includes #include // for LUABIND_API #include #include // Library/third-party includes #include // for lua_pushstring, lua_rawset, etc // Standard includes // - none static int do_set_package_preload(lua_State* L) { // Note: Use ordinary set/get instead of the raw variants, because this // function should not be performance sensitive anyway. lua_pushglobaltable(L); lua_getfield(L, -1, "package"); lua_remove(L, -2); // Remove global table. lua_getfield(L, -1, "preload"); lua_remove(L, -2); // Remove package table. lua_insert(L, -3); // Move package.preload beneath key and value. lua_settable(L, -3); // package.preload[modulename] = loader return 0; } static int proxy_loader(lua_State* L) { luaL_checkstring(L, 1); // First argument should be the module name. lua_settop(L, 1); // Ignore any other arguments. lua_pushvalue(L, lua_upvalueindex(1)); // Push the real loader. lua_insert(L, 1); // Move it beneath the argument. lua_call(L, 1, LUA_MULTRET); // Pops everyhing. return lua_gettop(L); } namespace luabind { LUABIND_API void set_package_preload( lua_State * L, char const* modulename, object const& loader) { loader.push(L); lua_pushcclosure(L, &proxy_loader, 1); object const proxy_ldr(from_stack(L, -1)); lua_pop(L, 1); // pop do_load. lua_pushcfunction(L, &do_set_package_preload); // Must use object for correct popping in case of errors: object do_set(from_stack(L, -1)); lua_pop(L, 1); do_set(modulename, proxy_ldr); } } // namespace luabind luabind-1.1.1/src/shared_ptr_converter.cpp000066400000000000000000000026461366245310300206600ustar00rootroot00000000000000#define LUABIND_BUILDING #include #include static char state_unreferenced_callback_tag = 0; LUABIND_API char luabind::detail::state_use_count_tag = 0; void luabind::detail::shared_ptr_deleter::alter_use_count( lua_State* L, lua_Integer diff) { lua_rawgetp(L, LUA_REGISTRYINDEX, &state_use_count_tag); lua_Integer uc = lua_tointeger(L, -1) + diff; lua_pop(L, 1); assert(uc >= 0); lua_pushinteger(L, uc); lua_rawsetp(L, LUA_REGISTRYINDEX, &state_use_count_tag); if (!uc) { if (state_unreferenced_fun cb = get_state_unreferenced_callback(L)) cb(L); } } void luabind::set_state_unreferenced_callback( lua_State* L, state_unreferenced_fun cb) { lua_pushcfunction(L, reinterpret_cast(cb)); lua_rawsetp(L, LUA_REGISTRYINDEX, &state_unreferenced_callback_tag); } luabind::state_unreferenced_fun luabind::get_state_unreferenced_callback( lua_State* L) { lua_rawgetp(L, LUA_REGISTRYINDEX, &state_unreferenced_callback_tag); state_unreferenced_fun cb = reinterpret_cast( lua_tocfunction(L, -1)); lua_pop(L, 1); return cb; } bool luabind::is_state_unreferenced(lua_State* L) { lua_rawgetp(L, LUA_REGISTRYINDEX, &detail::state_use_count_tag); lua_Integer uc = lua_tointeger(L, -1); lua_pop(L, 1); assert(uc >= 0); return uc <= 0; } luabind-1.1.1/src/stack_content_by_name.cpp000066400000000000000000000045271366245310300207670ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include #include // for class_rep, is_class_rep #include // for declaration of stack_content_by_name #include // for get_instance, object_rep #include // for lua_gettop, lua_touserdata, etc #include // for string using namespace luabind::detail; LUABIND_API std::string luabind::detail::stack_content_by_name(lua_State* L, int start_index) { std::string ret; int top = lua_gettop(L); for (int i = start_index; i <= top; ++i) { object_rep* obj = get_instance(L, i); class_rep* crep = is_class_rep(L, i) ? static_cast(lua_touserdata(L, i)) : 0; if (obj == 0 && crep == 0) { int type = lua_type(L, i); ret += lua_typename(L, type); } else if (obj) { if (obj->is_const()) ret += "const "; ret += obj->crep()->name(); } else if (crep) { ret += "<"; ret += crep->name(); ret += ">"; } if (i < top) ret += ", "; } return ret; } luabind-1.1.1/src/weak_ref.cpp000066400000000000000000000102671366245310300162170ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include #include #include #include #include namespace luabind { namespace { int weak_table_tag; int impl_table_tag; void get_weak_table(lua_State* L) { lua_rawgetp(L, LUA_REGISTRYINDEX, &weak_table_tag); if (lua_isnil(L, -1)) { lua_pop(L, 1); lua_newtable(L); // metatable lua_createtable(L, 0, 1); // One non-sequence entry for __mode. lua_pushliteral(L, "__mode"); lua_pushliteral(L, "v"); lua_rawset(L, -3); // set metatable lua_setmetatable(L, -2); lua_pushvalue(L, -1); lua_rawsetp(L, LUA_REGISTRYINDEX, &weak_table_tag); } } void get_impl_table(lua_State* L) { lua_pushlightuserdata(L, &impl_table_tag); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_isnil(L, -1)) { lua_pop(L, 1); lua_newtable(L); lua_pushvalue(L, -1); lua_rawsetp(L, LUA_REGISTRYINDEX, &impl_table_tag); } } } // namespace unnamed struct weak_ref::impl { impl(lua_State* main, lua_State* s, int index) : state(main) , count(0) , ref(0) { get_impl_table(s); lua_pushlightuserdata(s, this); ref = luaL_ref(s, -2); lua_pop(s, 1); get_weak_table(s); lua_pushvalue(s, index); lua_rawseti(s, -2, ref); lua_pop(s, 1); } ~impl() { get_impl_table(state); luaL_unref(state, -1, ref); lua_pop(state, 1); } lua_State* state; int count; int ref; }; weak_ref::weak_ref() : m_impl(0) { } weak_ref::weak_ref(lua_State* main, lua_State* L, int index) : m_impl(new impl(main, L, index)) { m_impl->count = 1; } weak_ref::weak_ref(weak_ref const& other) : m_impl(other.m_impl) { if (m_impl) ++m_impl->count; } weak_ref::~weak_ref() { if (m_impl && --m_impl->count == 0) { delete m_impl; } } weak_ref& weak_ref::operator=(weak_ref const& other) { weak_ref(other).swap(*this); return *this; } void weak_ref::swap(weak_ref& other) { std::swap(m_impl, other.m_impl); } int weak_ref::id() const { assert(m_impl); return m_impl->ref; } // L may not be the same pointer as // was used when creating this reference // since it may be a thread that shares // the same globals table. void weak_ref::get(lua_State* L) const { assert(m_impl); assert(L); get_weak_table(L); lua_rawgeti(L, -1, m_impl->ref); lua_remove(L, -2); } lua_State* weak_ref::state() const { assert(m_impl); return m_impl->state; } } // namespace luabind luabind-1.1.1/src/wrapper_base.cpp000066400000000000000000000040431366245310300171010ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include #include #include #include #include #include namespace luabind { namespace detail { LUABIND_API void do_call_member_selection(lua_State* L, char const* name) { object_rep* obj = static_cast(lua_touserdata(L, -1)); assert(obj); lua_pushstring(L, name); lua_gettable(L, -2); lua_replace(L, -2); if (!is_luabind_function(L, -1)) return; // this (usually) means the function has not been // overridden by lua, call the default implementation lua_pop(L, 1); obj->crep()->get_default_table(L); // push the crep table lua_pushstring(L, name); lua_gettable(L, -2); lua_remove(L, -2); // remove the crep table } }} luabind-1.1.1/test/000077500000000000000000000000001366245310300141125ustar00rootroot00000000000000luabind-1.1.1/test/CMakeLists.txt000066400000000000000000000074611366245310300166620ustar00rootroot00000000000000# Build for LuaBind # Ryan Pavlik # http://academic.cleardefinition.com/ # Iowa State University HCI Graduate Program/VRAC # ls test_*.cpp | sort | sed -e 's/test_//' -e 's/.cpp//' -e 's/^/ /' | grep -v "has_get_pointer" # This command removes has_get_pointer because it is a compile-only test set(TESTS abstract_base adopt adopt_wrapper attributes automatic_smart_ptr back_reference builtin_converters class_info collapse_converter const construction create_in_thread def_from_base destruction dynamic_type exception_handlers exceptions extend_class_in_lua free_functions function_converter function_introspection function_object function_overload_overflow held_type implicit_cast implicit_raw intrusive_ptr iterator lua_classes null_pointer object operators # out_value // Currently fails to compile package_preload policies private_destructors properties scope separation set_instance_value shadow shared_ptr simple_class smart_ptr_attributes super_leak table tag_function typetraits unchecked unsigned_int user_defined_converter value_wrapper vector_of_object vector_of_number virtual_inheritance yield) add_library(test_main STATIC main.cpp test.hpp # These tests consist only of compile time asserts and define no test_main # function: test_has_get_pointer.cpp) if (BUILD_SHARED_LIBS AND MSVC) add_custom_command(TARGET test_main POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy $ $ COMMENT "Copying DLL...") endif() foreach(test ${TESTS}) add_executable(test_${test} test_${test}.cpp) target_link_libraries(test_${test} test_main luabind) add_test(NAME ${test} COMMAND test_${test}) set_property(TARGET test_${test} PROPERTY FOLDER "Tests") endforeach() if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang" AND LUABIND_ENABLE_WARNINGS) set (priv_dtor_flags "-Wno-ctor-dtor-privacy") if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") set(priv_dtor_flags "${priv_dtor_flags} -Wno-unused-member-function") endif() set_property(TARGET test_private_destructors PROPERTY COMPILE_FLAGS "${priv_dtor_flags}") set_property(TARGET test_builtin_converters PROPERTY COMPILE_FLAGS "-Wno-float-equal") endif() add_executable(benchmark "benchmark.cpp") target_link_libraries(benchmark ${LUA_LIBRARIES} luabind) option(LUABIND_BUILD_HEADER_TESTS "Try to compile every header in the luabind directory, excluding detail headers, in its own translation unit, to check for missing includes." OFF) if(BUILD_TESTING AND LUABIND_BUILD_HEADER_TESTS) get_filename_component(BASE "${CMAKE_CURRENT_SOURCE_DIR}/../luabind" ABSOLUTE) foreach(HEADER ${APIHEADERS}) get_filename_component(FULLHEADER "${HEADER}" ABSOLUTE) file(RELATIVE_PATH SHORTNAME "${BASE}" "${FULLHEADER}") string(REPLACE "/" "_" SHORTNAME "${SHORTNAME}") string(REPLACE ".hpp" "" SHORTNAME "${SHORTNAME}") set (targetname test_headercompile_${SHORTNAME}) set (cppname "${CMAKE_CURRENT_BINARY_DIR}/${targetname}.cpp") configure_file(test_headercompile.cpp.in "${cppname}" @ONLY) add_executable(${targetname} ${cppname}) if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND LUABIND_ENABLE_WARNINGS) # Clang complains about '#define LUABIND_TEST_HEADERCOMPILE'. set_property(TARGET ${targetname} PROPERTY COMPILE_FLAGS "-Wno-unused-macros") endif() set_property(TARGET ${targetname} PROPERTY FOLDER "Tests/Headers") target_link_libraries(${targetname} luabind) endforeach() endif() luabind-1.1.1/test/benchmark.cpp000066400000000000000000000041601366245310300165510ustar00rootroot00000000000000#include #include namespace std { using ::clock_t; // using ::clock; } #include #ifndef LUABIND_CPLUSPLUS_LUA extern "C" { #endif #include "lua.h" #include "lauxlib.h" #ifndef LUABIND_CPLUSPLUS_LUA } #endif #include struct A {}; // luabind function static float f1(int, float, const char*, A*) { return 3.14f; } // empty function static int f2(lua_State*) { return 0; } inline double clocks_to_seconds(std::clock_t c) { return static_cast(c) / CLOCKS_PER_SEC; } int main() { const int num_calls = 100000; const int loops = 10; using namespace luabind; lua_State* L = luaL_newstate(); open(L); module(L) [ class_("A") .def(constructor<>()), def("test1", &f1) ]; lua_pushcclosure(L, &f2, 0); lua_setglobal(L, "test2"); std::clock_t total1 = 0; std::clock_t total2 = 0; for (int i = 0; i < loops; ++i) { // benchmark luabind std::clock_t start1 = std::clock(); luaL_dostring(L, "a = A()\n" " for i = 1, 100000 do\n" " test1(5, 4.6, 'foo', a)\n" "end"); std::clock_t end1 = std::clock(); // benchmark empty binding std::clock_t start2 = std::clock(); luaL_dostring(L, "a = A()\n" "for i = 1, 100000 do\n" " test2(5, 4.6, 'foo', a)\n" "end"); std::clock_t end2 = std::clock(); total1 += end1 - start1; total2 += end2 - start2; } double time1 = clocks_to_seconds(total1); double time2 = clocks_to_seconds(total2); #ifdef LUABIND_NO_ERROR_CHECKING std::cout << "without error-checking\n"; #endif std::cout << "luabind: " << time1 * 1000000 / num_calls / loops << " microseconds per call\n" << "empty : " << time2 * 1000000 / num_calls / loops << " microseconds per call\n" << "diff : " << ((time1 - time2) * 1000000 / num_calls / loops) << " microseconds\n\n"; lua_close(L); } luabind-1.1.1/test/main.cpp000066400000000000000000000070431366245310300155460ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin, Arvid Norberg // 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. #include "test.hpp" #include #ifndef LUABIND_CPLUSPLUS_LUA extern "C" { #endif # include #ifndef LUABIND_CPLUSPLUS_LUA } #endif #include // for open #include // for strlen #include // for exception #include // for operator<<, basic_ostream, etc #include // for string struct lua_state { lua_state(); ~lua_state(); operator lua_State*() const; void check() const; private: lua_State* m_state; int m_top; }; lua_state::lua_state() : m_state(luaL_newstate()) { luaopen_base(m_state); #if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 501 // lua 5.1 or newer luaL_openlibs(m_state); #else // lua 5.0.2 or older lua_baselibopen(m_state); #endif m_top = lua_gettop(m_state); luabind::open(m_state); } lua_state::~lua_state() { lua_close(m_state); } void lua_state::check() const { TEST_CHECK(lua_gettop(m_state) == m_top); } lua_state::operator lua_State*() const { return m_state; } static int pcall_handler(lua_State*) { return 1; } void dostring(lua_State* state, char const* str) { lua_pushcclosure(state, &pcall_handler, 0); if (luaL_loadbuffer(state, str, std::strlen(str), str)) { std::string err(lua_tostring(state, -1)); lua_pop(state, 2); throw err; } if (lua_pcall(state, 0, 0, -2)) { std::string err(lua_tostring(state, -1)); lua_pop(state, 2); throw err; } lua_pop(state, 1); } static bool tests_failure = false; void report_failure(char const* err, char const* file, int line) { std::cerr << file << ":" << line << "\"" << err << "\"\n"; tests_failure = true; } int main() { lua_state L; #ifndef LUABIND_NO_EXCEPTIONS try { #endif test_main(L); L.check(); return tests_failure ? 1 : 0; #ifndef LUABIND_NO_EXCEPTIONS } catch (luabind::error const& e) { std::cerr << "Terminated with exception: \"" << e.what() << "\"\n" << lua_tostring(e.state(), -1) << "\n"; return 1; } catch (std::exception const& e) { std::cerr << "Terminated with exception: \"" << e.what() << "\"\n"; return 1; } catch (...) { std::cerr << "Terminated with unknown exception\n"; return 1; } #endif } luabind-1.1.1/test/test.hpp000066400000000000000000000102101366245310300155740ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin, Arvid Norberg // 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. #ifndef TEST_050415_HPP #define TEST_050415_HPP #include #include #include #include // See boost/exception/detail/attribute_noreturn.hpp #if defined(BOOST_CLANG) // Clang's noreturn changes the type so that it is not recognizable by // Boost.FunctionTypes. # define LUABIND_ATTRIBUTE_NORETURN #elif defined(_MSC_VER) # define LUABIND_ATTRIBUTE_NORETURN __declspec(noreturn) #elif defined(__GNUC__) # define LUABIND_ATTRIBUTE_NORETURN __attribute__((__noreturn__)) #else # define LUABIND_ATTRIBUTE_NORETURN #endif // Individual tests must provide a definition for this function: void test_main(lua_State* L); void report_failure(char const* str, char const* file, int line); #if defined(_MSC_VER) #define COUNTER_GUARD(x) #else #define COUNTER_GUARD(type) \ struct BOOST_PP_CAT(type, _counter_guard) \ { \ ~BOOST_PP_CAT(type, _counter_guard()) \ { \ TEST_CHECK(counted_type::count == 0); \ } \ } BOOST_PP_CAT(type, _guard) #endif #define TEST_REPORT_AUX(x, line, file) \ report_failure(x, line, file) #define TEST_CHECK(x) \ if (!(x)) \ TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__) #define TEST_ERROR(x) \ TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__) #define TEST_NOTHROW(x) \ try \ { \ x; \ } \ catch (...) \ { \ TEST_ERROR("Exception thrown: " #x); \ } void dostring(lua_State* L, char const* str); template struct counted_type { static int count; counted_type() { ++count; } counted_type(counted_type const&) { ++count; } ~counted_type() { TEST_CHECK(--count >= 0); } }; template int counted_type::count = 0; #define DOSTRING_EXPECTED(state_, str, expected) \ { \ try \ { \ dostring(state_, str); \ } \ catch (std::string const& s) \ { \ if (s.find(expected) == std::string::npos) \ TEST_ERROR("Expected error '" \ + expected + "' but got '" + s + "'"); \ } \ } #define DOSTRING(state_, str) \ { \ try \ { \ dostring(state_, str); \ } \ catch (std::string const& s) \ { \ TEST_ERROR(s.c_str()); \ } \ } #endif // TEST_050415_HPP luabind-1.1.1/test/test_abstract_base.cpp000066400000000000000000000060351366245310300204560ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include using namespace luabind; namespace { struct abstract { virtual ~abstract() {} virtual std::string hello() = 0; }; COUNTER_GUARD(abstract); struct concrete : abstract { std::string hello() { return "test string"; } }; struct abstract_wrap : abstract, wrap_base { std::string hello() { return call_member(this, "hello"); } }; static std::string call_hello(abstract& a) { return a.hello(); } static abstract& return_abstract_ref() { static concrete c; return c; } static abstract const& return_const_abstract_ref() { static concrete c; return c; } } // namespace unnamed void test_main(lua_State* L) { module(L) [ class_("abstract") .def(constructor<>()) .def("hello", &abstract::hello), def("call_hello", &call_hello), def("return_abstract_ref", &return_abstract_ref), def("return_const_abstract_ref", &return_const_abstract_ref) ]; DOSTRING_EXPECTED(L, "x = abstract()\n" "x:hello()\n" , "std::runtime_error: 'Attempt to call nonexistent function'"); DOSTRING_EXPECTED(L, "call_hello(x)\n" , "std::runtime_error: 'Attempt to call nonexistent function'"); DOSTRING(L, "class 'concrete' (abstract)\n" " function concrete:__init()\n" " abstract.__init(self)\n" " end\n" " function concrete:hello()\n" " return 'hello from lua'\n" " end\n"); DOSTRING(L, "y = concrete()\n" "y:hello()\n"); DOSTRING(L, "call_hello(y)\n"); DOSTRING(L, "x = abstract()\n" "x.hello = function(self) return 'hello from instance' end\n" "print(x.hello)\n" "assert(x:hello() == 'hello from instance')\n" "assert(call_hello(x) == 'hello from instance')\n" ); } luabind-1.1.1/test/test_adopt.cpp000066400000000000000000000063201366245310300167650ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include #include #include namespace { struct Base { Base() { count++; } virtual ~Base() { count--; } static int count; }; int Base::count = 0; struct Base_wrap : Base, luabind::wrap_base {}; Base* adopted = 0; void take_ownership(Base* p) { adopted = p; } void not_null(Base* p) { TEST_CHECK(p); } } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; disable_super_deprecation(); module(L) [ class_("Base") .def(constructor<>()), def("take_ownership", &take_ownership, adopt(_1)), def("not_null", ¬_null) ]; DOSTRING(L, "x = Base()\n" ); TEST_CHECK(Base::count == 1); DOSTRING(L, "x = nil\n" "collectgarbage('collect')\n" ); TEST_CHECK(Base::count == 0); DOSTRING(L, "class 'Derived' (Base)\n" " function Derived:__init()\n" " super()\n" " self.x = Base()\n" " end\n" ); DOSTRING(L, "x = Derived()\n" ); TEST_CHECK(Base::count == 2); DOSTRING(L, "x = nil\n" "collectgarbage('collect')\n" "collectgarbage('collect')\n" ); TEST_CHECK(Base::count == 0); DOSTRING(L, "x = nil\n" "collectgarbage('collect')\n" ); TEST_CHECK(Base::count == 0); DOSTRING(L, "class 'Derived2' (Derived)\n" " function Derived2:__init()\n" " super()\n" " end\n" ); DOSTRING(L, "x = Derived2()\n" ); TEST_CHECK(Base::count == 2); DOSTRING(L, "x = nil\n" "collectgarbage('collect')\n" "collectgarbage('collect')\n" ); TEST_CHECK(Base::count == 0); DOSTRING(L, "x = Derived()\n" ); TEST_CHECK(Base::count == 2); DOSTRING(L, "take_ownership(x)\n" "x = nil\n" "collectgarbage('collect')\n" "collectgarbage('collect')\n" ); TEST_CHECK(Base::count == 2); delete adopted; DOSTRING(L, "collectgarbage('collect')\n" "collectgarbage('collect')\n" ); TEST_CHECK(Base::count == 0); DOSTRING(L, "x = Derived2()\n" ); TEST_CHECK(Base::count == 2); DOSTRING(L, "take_ownership(x)\n" "x = nil\n" "collectgarbage('collect')\n" "collectgarbage('collect')\n" ); TEST_CHECK(Base::count == 2); delete adopted; DOSTRING(L, "collectgarbage('collect')\n" "collectgarbage('collect')\n" ); TEST_CHECK(Base::count == 0); DOSTRING(L, "x = Derived()\n" "take_ownership(x)\n" "not_null(x)\n" ); delete adopted; DOSTRING(L, "x = nil\n" "collectgarbage('collect')\n" ); TEST_CHECK(Base::count == 0); DOSTRING(L, "take_ownership(nil)\n" ); TEST_CHECK(adopted == 0); } luabind-1.1.1/test/test_adopt_wrapper.cpp000066400000000000000000000013451366245310300205270ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include #include namespace { struct X { virtual ~X() {} }; struct X_wrap : X, luabind::wrap_base {}; X* make() { return new X; } void take(X* p) { delete p; } } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("X"), def("make", &make, adopt(result)), def("take", &take, adopt(_1)) ]; DOSTRING(L, "take(make())\n" ); } luabind-1.1.1/test/test_attributes.cpp000066400000000000000000000130541366245310300200460ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include namespace { struct A { int get() const { return 5; } }; struct B : A { }; struct C { int a; }; struct property_test : counted_type { property_test(): c_ref(&c), o(6) {} ~property_test() { c.a = 0; } std::string str_; C* c_ref; C c; float o; int a_; signed char b; void set(int a) { a_ = a; } int get() const { return a_; } void setA(A*) {} A* getA() const { return 0; } void set_str(const char* str) { str_ = str; } const char* get_str() const { return str_.c_str(); } }; COUNTER_GUARD(property_test); void free_setter(property_test& p, int a) { p.set(a); } int free_getter(const property_test& p) { return p.get(); } } // namespace unnamed struct borrowed_attribute : counted_type { }; struct attribute_holder : counted_type { attribute_holder(borrowed_attribute* b) : borrowed(b) {} borrowed_attribute* borrowed; }; void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("property") .def(luabind::constructor<>()) .def("get", &property_test::get) .property("a", &property_test::get, &property_test::set) .property("str", &property_test::get_str, &property_test::set_str) .property("A", &property_test::getA, &property_test::setA) .def_readonly("o", &property_test::o) .property("free", &free_getter, &free_setter) .def_readwrite("b", &property_test::b) .def_readwrite("c", &property_test::c) .def_readwrite("c_ref", &property_test::c_ref), class_("A") .def(constructor<>()) .property("a", &A::get), class_("B") .def(constructor<>()) .property("x", &A::get), class_("C") .def(constructor<>()) .def_readwrite("a", &C::a) ]; DOSTRING(L, "test = property()\n"); DOSTRING(L, "test.a = 5\n" "assert(test.a == 5)"); DOSTRING(L, "assert(test.o == 6)"); DOSTRING(L, "test.new_member = 'foo'\n" "assert(test.new_member == 'foo')"); DOSTRING(L, "property.new_member2 = 'bar'\n" "assert(property.new_member2 == 'bar')"); DOSTRING(L, "b = property()\n" "assert(b.new_member2 == 'bar')"); DOSTRING(L, "test.str = 'foobar'\n" "assert(test.str == 'foobar')\n"); module(L) [ class_("borrowed_attribute") .def(constructor<>()), class_("attribute_holder") .def(constructor()) .def_readwrite( "borrowed", &attribute_holder::borrowed, no_dependency) ]; DOSTRING(L, "test = property()\n"); DOSTRING(L, "test.a = 5\n" "assert(test.a == 5)"); DOSTRING(L, "assert(test.o == 6)"); DOSTRING(L, "test.new_member = 'foo'\n" "assert(test.new_member == 'foo')"); DOSTRING(L, "property.new_member2 = 'bar'\n" "assert(property.new_member2 == 'bar')"); DOSTRING(L, "b = property()\n" "assert(b.new_member2 == 'bar')"); DOSTRING(L, "test.str = 'foobar'\n" "assert(test.str == 'foobar')\n"); DOSTRING(L, "test.free = 6\n" "assert(test.free == 6)\n"); DOSTRING(L, "test.b = 3\n" "assert(test.b == 3)\n"); DOSTRING(L, "test.c.a = 1\n" "assert(test.c.a == 1)\n" "assert(test.c_ref.a == 1)"); DOSTRING(L, "t1 = property()\n" "c = t1.c\n" "c2 = t1.c_ref\n" "c.a = 1\n" "t1 = nil\n" "collectgarbage()\n" "collectgarbage()\n" "assert(c.a == 1)\n" "assert(c2.a == 1)"); DOSTRING(L, "a = B()\n"); DOSTRING(L, "assert(a.a == 5)\n"); DOSTRING(L, "assert(a.x == 5)\n"); DOSTRING(L, "borrowed = borrowed_attribute()\n" "holder = attribute_holder(borrowed)\n" ); TEST_CHECK(borrowed_attribute::count == 1); TEST_CHECK(attribute_holder::count == 1); DOSTRING(L, "holder.borrowed = borrowed\n" "borrowed2 = holder.borrowed\n" "holder = nil\n" "collectgarbage()\n" ); TEST_CHECK(borrowed_attribute::count == 1); TEST_CHECK(attribute_holder::count == 0); } luabind-1.1.1/test/test_automatic_smart_ptr.cpp000066400000000000000000000050611366245310300217400ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include #include namespace { struct X { X(int value_) : value(value_) { ++alive; } ~X() { --alive; } int value; static int alive; }; int X::alive = 0; struct D: X { D(int value_): X(value_) {} }; struct ptr { ptr(X* p_) : p(p_) {} ptr(ptr const& other) : p(other.p) { const_cast(other).p = 0; } ~ptr() { delete p; } X* p; }; X* get_pointer(ptr const& p) { return p.p; } #ifdef LUABIND_USE_CXX11 std::unique_ptr make1() { return std::unique_ptr(new X(1)); } #else std::auto_ptr make1() { return std::auto_ptr(new X(1)); } #endif boost::shared_ptr make2() { return boost::shared_ptr(new X(2)); } ptr make3() { return ptr(new X(3)); } boost::shared_ptr make_d() { return boost::shared_ptr(new D(10)); } void needs_x(boost::shared_ptr) {} } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("X") .def_readonly("value", &X::value), class_("D"), def("make1", make1), def("make2", make2), def("make3", make3), def("make_d", make_d), def("needs_x", needs_x) ]; DOSTRING(L, "x1 = make1()\n" "x2 = make2()\n" "x3 = make3()\n" ); TEST_CHECK(X::alive == 3); DOSTRING(L, "assert(x1.value == 1)\n" "assert(x2.value == 2)\n" "assert(x3.value == 3)\n" ); DOSTRING(L, "function get2() return x2 end"); boost::shared_ptr spx = call_function >(L, "get2"); TEST_CHECK(spx.use_count() == 2); DOSTRING(L, "x1 = nil\n" "x2 = nil\n" "x3 = nil\n" "collectgarbage()\n" ); TEST_CHECK(spx.use_count() == 1); TEST_CHECK(X::alive == 1); spx.reset(); TEST_CHECK(X::alive == 0); DOSTRING(L, "d = make_d()\n" "status, err = pcall(needs_x, d)\n" "assert(not status)\n" "pat = '^No matching overload found, candidates:\\n'\n" "pat = pat .. 'void needs_x%(custom %[.+%]%)$'\n" "if not err:match(pat) then\n" " error('expected \"' .. pat .. '\", got \"' .. err .. '\"')\n" "end\n" ); } luabind-1.1.1/test/test_back_reference.cpp000066400000000000000000000046401366245310300205770ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin // 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. #include "test.hpp" #include #include using namespace luabind; #ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP namespace luabind { using boost::get_pointer; } #endif namespace { struct base0 { virtual ~base0() {} }; struct base_wrap0 : base0, wrap_base {}; struct base1 { virtual ~base1() {} }; struct base_wrap1 : base1, wrap_base {}; base0* filter0(base0* p) { return p; } boost::shared_ptr filter1(boost::shared_ptr const& p) { return p; } } // namespace unnamed void test_main(lua_State* L) { module(L) [ class_("base0") .def(constructor<>()), def("filter0", &filter0), class_ >("base1") .def(constructor<>()), def("filter1", &filter1) ]; DOSTRING(L, "class 'derived0' (base0)\n" " function derived0:__init()\n" " base0.__init(self)\n" " end\n" "class 'derived1' (base1)\n" " function derived1:__init()\n" " base1.__init(self)\n" " end\n" ); DOSTRING(L, "x = derived0()\n" "y = filter0(x)\n" "assert(x == y)\n" ); DOSTRING(L, "x = derived1()\n" "y = filter1(x)\n" "assert(x == y)\n" ); } luabind-1.1.1/test/test_builtin_converters.cpp000066400000000000000000000035151366245310300216010ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include #define LUABIND_TEST_BUILTIN(type, value) \ default_converter().to(L, value); \ default_converter BOOST_PP_CAT(cv, __LINE__); \ TEST_CHECK(BOOST_PP_CAT(cv, __LINE__).compute_score(L, -1) >= 0); \ TEST_CHECK(BOOST_PP_CAT(cv, __LINE__).from(L, -1) == value); \ lua_pop(L, 1) void test_main(lua_State* L) { using namespace luabind; LUABIND_TEST_BUILTIN(int, 1); LUABIND_TEST_BUILTIN(int, -1); LUABIND_TEST_BUILTIN(unsigned int, 1u); LUABIND_TEST_BUILTIN(unsigned int, 2u); LUABIND_TEST_BUILTIN(short, static_cast(1)); LUABIND_TEST_BUILTIN(short, static_cast(-1)); LUABIND_TEST_BUILTIN(unsigned short, static_cast(1)); LUABIND_TEST_BUILTIN(unsigned short, static_cast(2)); LUABIND_TEST_BUILTIN(long, 1L); LUABIND_TEST_BUILTIN(long, -1L); LUABIND_TEST_BUILTIN(unsigned long, 1uL); LUABIND_TEST_BUILTIN(unsigned long, 2uL); LUABIND_TEST_BUILTIN(char, '\1'); LUABIND_TEST_BUILTIN(char, '\2'); LUABIND_TEST_BUILTIN(unsigned char, static_cast(1)); LUABIND_TEST_BUILTIN(unsigned char, static_cast(2)); LUABIND_TEST_BUILTIN(signed char, static_cast(-1)); LUABIND_TEST_BUILTIN(signed char, static_cast(1)); LUABIND_TEST_BUILTIN(float, 1.5f); LUABIND_TEST_BUILTIN(float, -1.5f); LUABIND_TEST_BUILTIN(double, 1.5); LUABIND_TEST_BUILTIN(double, -1.5); LUABIND_TEST_BUILTIN(bool, true); LUABIND_TEST_BUILTIN(bool, false); } luabind-1.1.1/test/test_class_info.cpp000066400000000000000000000035061366245310300200010ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include #include struct X { void f() {} int x; int y; }; void test_main(lua_State* L) { using namespace luabind; bind_class_info(L); module(L) [ class_("X") .def(constructor<>()) .def("f", &X::f) .def_readonly("x", &X::x) .def_readonly("y", &X::y) ]; DOSTRING(L, "x = X()\n" "info = class_info(x)\n" "assert(info.name == 'X')\n" "assert(info.methods['f'] == x.f)\n" "assert(info.methods['__init'] == x.__init)\n" "attrs = info.attributes\n" "assert(attrs[1] == 'x' or attrs[2] == 'x')\n" "assert(attrs[1] == 'y' or attrs[2] == 'y')\n" "info = class_info(2)\n" "assert(info.name == 'number')\n" "assert(#info.methods == 0)\n" "assert(#info.attributes == 0)\n" "names = class_names()\n" "assert(type(names) == 'table')\n" "assert(#names == 2)\n" "assert(names[1] == 'X' or names[2] == 'X')\n" "assert(names[1] == 'class_info_data' or names[2] == 'class_info_data')\n"); DOSTRING(L, "info = class_info(X)\n" "assert(info.name == 'X')\n" "assert(info.methods['f'] == X().f)\n" "assert(info.methods['__init'] == X().__init)\n" "attrs = info.attributes\n" "assert(attrs[1] == 'x' or attrs[2] == 'x')\n" "assert(attrs[1] == 'y' or attrs[2] == 'y')\n" ); DOSTRING(L, "s = tostring(X)\n" "assert(s:match('^class X (.+)$'))" ); DOSTRING(L, "print(X)"); } luabind-1.1.1/test/test_collapse_converter.cpp000066400000000000000000000024701366245310300215510ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include namespace { struct X { X(lua_Integer x_, lua_Integer y_) : x(x_) , y(y_) {} lua_Integer x; lua_Integer y; }; lua_Integer take(X x) { return x.x + x.y; } } // namespace unnamed namespace luabind { static int combine_score(int s1, int s2) { if (s1 < 0 || s2 < 0) return -1; return s1 + s2; } template <> struct default_converter : native_converter_base { int consumed_args() const { return 2; } int compute_score(lua_State* L, int index) { return combine_score( c1.compute_score(L, index), c2.compute_score(L, index + 1)); } X from(lua_State* L, int index) { return X(lua_tointeger(L, index), lua_tointeger(L, index + 1)); } default_converter c1; default_converter c2; }; } // namespace luabind void test_main(lua_State* L) { using namespace luabind; module(L) [ def("take", &take) ]; DOSTRING(L, "assert(take(1,1) == 2)\n" "assert(take(2,3) == 5)\n" ); } luabind-1.1.1/test/test_const.cpp000066400000000000000000000032041366245310300170020ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include struct A { const A* f() { return this; } int g1() const { return 1; } int g2() { return 2; } }; void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("A") .def(constructor<>()) .def("f", &A::f) .def("g", &A::g1) .def("g", &A::g2) ]; DOSTRING(L, "a = A()"); DOSTRING(L, "assert(a:g() == 2)"); DOSTRING(L, "a2 = a:f()"); DOSTRING(L, "assert(a2:g() == 1)"); } luabind-1.1.1/test/test_construction.cpp000066400000000000000000000052131366245310300204100ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include namespace { struct A : counted_type { int test; A(int a) { test = a; } // Explicit call to default ctor to avoid g++'s "warning: base class // ‘struct counted_type’ should be explicitly initialized in the copy // constructor [-Wextra]" A(const A&): counted_type() { test = 1; } // A() { test = 2; } ~A() {} }; void f(A*, const A&) {} struct B: A, counted_type { int test2; B(int a):A(a) { test2 = a; } B() { test2 = 3; } ~B() {} }; struct C : counted_type {}; COUNTER_GUARD(A); COUNTER_GUARD(B); COUNTER_GUARD(C); } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("A") .def("f", &f) .def_readonly("test", &A::test) .def(constructor()) .def(constructor()) .def(constructor<>()), class_("B") .def(constructor()) .def(constructor<>()) .def_readonly("test2", &B::test2), class_("C") ]; DOSTRING_EXPECTED(L, "a = C()", "attempt to call a nil value"); DOSTRING(L, "a = A(4)\n" "assert(a.test == 4)"); DOSTRING(L, "a2 = A(a)\n" "assert(a2.test == 1)"); DOSTRING(L, "b = B(6)\n" "assert(b.test2 == 6)\n"); DOSTRING(L, "assert(b.test == 6)"); DOSTRING(L, "b2 = B()\n" "assert(b2.test2 == 3)\n"); DOSTRING(L, "assert(b2.test == 2)"); } luabind-1.1.1/test/test_create_in_thread.cpp000066400000000000000000000022361366245310300211400ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include namespace { int count = 0; struct X { X() { ++count; } ~X() { --count; } }; struct Y { virtual ~Y() {} }; struct Y_wrap : Y, luabind::wrap_base {}; } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("X") .def(constructor<>()), class_("Y") .def(constructor<>()) ]; DOSTRING(L, "class 'Y_lua' (Y)\n" " function Y_lua.__init(self)\n" " Y.__init(self)\n" " end\n" ); for (int i = 0; i < 100; ++i) { lua_State* thread = lua_newthread(L); int ref = luaL_ref(L, LUA_REGISTRYINDEX); DOSTRING(thread, "local x = X()\n" ); DOSTRING(thread, "local y = Y_lua()\n" ); luaL_unref(L, LUA_REGISTRYINDEX, ref); } } luabind-1.1.1/test/test_def_from_base.cpp000066400000000000000000000027501366245310300204340ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin, Arvid Norberg // 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. #include "test.hpp" #include struct V { int f(int,int) { return 2; } }; struct W : V {}; void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("W") .def(constructor<>()) .def("f", &V::f) ]; DOSTRING(L, "x = W()\n" "assert(x:f(1,2) == 2)\n" ); } luabind-1.1.1/test/test_destruction.cpp000066400000000000000000000015111366245310300202160ustar00rootroot00000000000000// Copyright Christian Neumüller 2013. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include struct CppClass { CppClass() { } void method() { } }; using namespace luabind; void test_main(lua_State* L) { module(L) [ class_("CppClass") .def(constructor<>()) .def("method", &CppClass::method) ]; DOSTRING_EXPECTED(L, "t = { }\n" "setmetatable(t, {__gc = function(t)\n" " t.cppClass:method() end})\n" "t.cppClass = CppClass()\n" "t = nil\n" "collectgarbage()\n" , "error in __gc metamethod ([string \"t = { }...\"]:3: attempt to index") } luabind-1.1.1/test/test_dynamic_type.cpp000066400000000000000000000030351366245310300203430ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include namespace { struct Base { Base(int value_) : value(value_) {} virtual ~Base() {} int g() const { return value; } int value; }; struct Derived : Base { Derived() : Base(2) {} int f() const { return 1; } }; struct Unregistered : Base { Unregistered() : Base(3) {} }; #ifdef LUABIND_USE_CXX11 std::unique_ptr make_derived() { return std::unique_ptr(new Derived); } std::unique_ptr make_unregistered() { return std::unique_ptr(new Unregistered); } #else std::auto_ptr make_derived() { return std::auto_ptr(new Derived); } std::auto_ptr make_unregistered() { return std::auto_ptr(new Unregistered); } #endif } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("Base") .def("g", &Base::g), class_("Derived") .def("f", &Derived::f), def("make_derived", &make_derived), def("make_unregistered", &make_unregistered) ]; DOSTRING(L, "x = make_derived()\n" "assert(x:f() == 1)\n" ); DOSTRING(L, "x = make_unregistered()\n" "assert(x:g() == 3)\n" ); } luabind-1.1.1/test/test_exception_handlers.cpp000066400000000000000000000033021366245310300215310ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include #include namespace { struct my_exception {}; void translate_my_exception(lua_State* L, my_exception const&) { lua_pushliteral(L, "my_exception"); } struct derived_std_exception : std::exception { char const* what() const LUABIND_NOEXCEPT { return "derived_std_exception"; } }; void translate_derived_exception(lua_State* L, derived_std_exception const&) { lua_pushliteral(L, "derived_std_exception"); } void LUABIND_ATTRIBUTE_NORETURN raise_my_exception() { throw my_exception(); } void LUABIND_ATTRIBUTE_NORETURN raise_derived() { throw derived_std_exception(); } } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; register_exception_handler(&translate_my_exception); module(L) [ def("raise", &raise_my_exception), def("raise_derived", &raise_derived) ]; DOSTRING(L, "status, msg = pcall(raise)\n" "assert(status == false)\n" "assert(msg == 'my_exception')\n"); DOSTRING(L, "status, msg = pcall(raise_derived)\n" "assert(status == false)\n" "assert(msg == 'std::exception: \\'derived_std_exception\\'')\n"); register_exception_handler(&translate_derived_exception); DOSTRING(L, "status, msg = pcall(raise_derived)\n" "assert(status == false)\n" "assert(msg == 'derived_std_exception')\n"); } luabind-1.1.1/test/test_exceptions.cpp000066400000000000000000000070321366245310300200400ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin // 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. #include "test.hpp" #include namespace { struct ex : public std::exception, public counted_type { ex(const char* m): msg(m) {} ex(ex const& rhs): msg(rhs.msg) {} virtual ~ex() LUABIND_NOEXCEPT {} virtual const char* what() const LUABIND_NOEXCEPT { return msg; } const char* msg; }; struct exception_thrower : counted_type { exception_thrower() {} #ifdef BOOST_MSVC # pragma warning(push) # pragma warning(disable:4702) // warning C4702: unreachable code #endif LUABIND_ATTRIBUTE_NORETURN exception_thrower(int) { throw ex("exception description"); } LUABIND_ATTRIBUTE_NORETURN exception_thrower(int, int) { throw "a string exception"; } LUABIND_ATTRIBUTE_NORETURN exception_thrower(int, int, int) { throw 10; } #ifdef BOOST_MSVC # pragma warning(pop) #endif int f() { throw ex("exception from a member function"); } int g() { throw "a string exception"; } int h() { throw 10; } }; COUNTER_GUARD(exception_thrower); } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; #ifndef LUABIND_NO_EXCEPTIONS const int start_count = ex::count; module(L) [ class_("throw") .def(constructor<>()) .def(constructor()) .def(constructor()) .def(constructor()) .def("f", &exception_thrower::f) .def("g", &exception_thrower::g) .def("h", &exception_thrower::h) ]; DOSTRING_EXPECTED(L, "a = throw(1)", "std::exception: 'exception description'"); DOSTRING_EXPECTED(L, "a = throw(1,1)", "c-string: 'a string exception'"); DOSTRING_EXPECTED(L, "a = throw(1,1,1)", "Unknown C++ exception"); DOSTRING(L, "a = throw()"); DOSTRING_EXPECTED(L, "a:f()", "std::exception: 'exception from a member function'"); DOSTRING_EXPECTED(L, "a:g()", "c-string: 'a string exception'"); DOSTRING_EXPECTED(L, "a:h()", "Unknown C++ exception"); DOSTRING_EXPECTED(L, "obj = throw('incorrect', 'parameters', 'constructor')", "No matching overload found, candidates:\n" "void __init(luabind::argument const&,int,int,int)\n" "void __init(luabind::argument const&,int,int)\n" "void __init(luabind::argument const&,int)\n" "void __init(luabind::argument const&)"); const int end_count = ex::count; TEST_CHECK( start_count == end_count ); #endif } luabind-1.1.1/test/test_extend_class_in_lua.cpp000066400000000000000000000014011366245310300216540ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include struct CppClass { int f(int x) { return x; } }; void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("CppClass") .def(constructor<>()) .def("f", &CppClass::f) ]; DOSTRING(L, "function CppClass:f_in_lua(x)\n" " return self:f(x) * 2\n" "end\n" ); DOSTRING(L, "x = CppClass()\n" "assert(x:f(1) == 1)\n" "assert(x:f_in_lua(1) == 2)\n" ); } luabind-1.1.1/test/test_free_functions.cpp000066400000000000000000000075321366245310300206750ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include #include namespace { struct base : counted_type { int f() { return 5; } }; COUNTER_GUARD(base); int f(int x) { return x + 1; } int f(int x, int y) { return x + y; } base* create_base() { return new base(); } void test_value_converter(const std::string str) { TEST_CHECK(str == "converted string"); } void test_pointer_converter(const char* const str) { TEST_CHECK(std::strcmp(str, "converted string") == 0); } struct copy_me { }; void take_by_value(copy_me) { } int function_should_never_be_called(lua_State* L) { lua_pushnumber(L, 10); return 1; } } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; lua_pushcclosure(L, &function_should_never_be_called, 0); lua_setglobal(L, "f"); DOSTRING(L, "assert(f() == 10)"); module(L) [ class_("copy_me") .def(constructor<>()), class_("base") .def("f", &base::f), def("by_value", &take_by_value), def("f", static_cast(&f)), def("f", static_cast(&f)), def("create", &create_base, adopt(return_value)) // def("set_functor", &set_functor) , def("test_value_converter", &test_value_converter), def("test_pointer_converter", &test_pointer_converter) ]; DOSTRING(L, "e = create()\n" "assert(e:f() == 5)"); DOSTRING(L, "assert(f(7) == 8)"); DOSTRING(L, "assert(f(3, 9) == 12)"); // DOSTRING(L, "set_functor(function(x) return x * 10 end)"); // TEST_CHECK(functor_test(20) == 200); // DOSTRING(L, "set_functor(nil)"); DOSTRING(L, "function lua_create() return create() end"); base* ptr = call_function(L, "lua_create") [ adopt(result) ]; delete ptr; DOSTRING(L, "test_value_converter('converted string')"); DOSTRING(L, "test_pointer_converter('converted string')"); DOSTRING_EXPECTED(L, "f('incorrect', 'parameters')", "No matching overload found, candidates:\n" "int f(int,int)\n" "int f(int)"); DOSTRING(L, "function failing_fun() error('expected error message') end"); try { call_function(L, "failing_fun"); TEST_ERROR("function didn't fail when it was expected to"); } catch (luabind::error const&) { if (std::string("[string \"function failing_fun() error('expected " #if LUA_VERSION_NUM >= 502 "error ..." #else "erro..." #endif "\"]:1: expected error message") != lua_tostring(L, -1)) { TEST_ERROR("function failed with unexpected error message"); } lua_pop(L, 1); } } luabind-1.1.1/test/test_function_converter.cpp000066400000000000000000000022721366245310300215740ustar00rootroot00000000000000// Copyright Christian Neumller 2013. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include #include namespace { int f(int x, int y) { return x + y; } struct X { int operator()(int x, int y) { return x + y; } }; typedef int(*f_type)(int, int); f_type function_test(boost::function g) { TEST_CHECK(g(3) == 9); return &f; } } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; globals(L)["f"] = &f; DOSTRING(L, "assert(f(1, 5) == 6)"); X x; globals(L)["f2"] = boost::function(x); DOSTRING(L, "assert(f2(4, 3) == 7)"); object free_f(L, &f); boost::function free_f_wrapped = object_cast >(free_f); TEST_CHECK(free_f_wrapped(2, 6) == 8); globals(L)["function_test"] = &function_test; DOSTRING(L, "local function sqr(n) return n * n end\n" "assert(function_test(sqr)(11, 12) == 23)" ); } luabind-1.1.1/test/test_function_introspection.cpp000066400000000000000000000072731366245310300224730ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // Copyright (c) 2012 Iowa State University // 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. #include "test.hpp" #include #include #include namespace { /* struct base : counted_type { int f() { return 5; } }; COUNTER_GUARD(base); */ int f(int x) { return x + 1; } /* int f(int x, int y) { return x + y; } */ } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; bind_function_introspection(L); DOSTRING(L, "assert(function_info.get_function_name)"); DOSTRING(L, "assert(function_info.get_function_overloads)"); module(L) [ def("f", static_cast(&f)) ]; DOSTRING(L, "assert(function_info.get_function_name(f) == 'f')"); DOSTRING(L, "assert(function_info.get_function_name(x) == '')"); DOSTRING(L, "for _,v in ipairs(function_info.get_function_overloads(f)) do print(v) end"); DOSTRING(L, "assert(#(function_info.get_function_overloads(f)) == 1)"); /* def("f", (int(*)(int, int)) &f), def("create", &create_base, adopt(return_value)) // def("set_functor", &set_functor) , def("test_value_converter", &test_value_converter), def("test_pointer_converter", &test_pointer_converter) ]; DOSTRING(L, "e = create()\n" "assert(e:f() == 5)"); DOSTRING(L, "assert(f(7) == 8)"); DOSTRING(L, "assert(f(3, 9) == 12)"); // DOSTRING(L, "set_functor(function(x) return x * 10 end)"); // TEST_CHECK(functor_test(20) == 200); // DOSTRING(L, "set_functor(nil)"); DOSTRING(L, "function lua_create() return create() end"); base* ptr = call_function(L, "lua_create") [ adopt(result) ]; delete ptr; DOSTRING(L, "test_value_converter('converted string')"); DOSTRING(L, "test_pointer_converter('converted string')"); DOSTRING_EXPECTED(L, "f('incorrect', 'parameters')", "No matching overload found, candidates:\n" "int f(int,int)\n" "int f(int)"); DOSTRING(L, "function failing_fun() error('expected error message') end"); try { call_function(L, "failing_fun"); TEST_ERROR("function didn't fail when it was expected to"); } catch(luabind::error const& e) { if (std::string("[string \"function failing_fun() error('expected " "erro...\"]:1: expected error message") != lua_tostring(L, -1)) { TEST_ERROR("function failed with unexpected error message"); } lua_pop(L, 1); } */ } luabind-1.1.1/test/test_function_object.cpp000066400000000000000000000027061366245310300210350ustar00rootroot00000000000000// Copyright Christian Neumller 2013. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include #include #if BOOST_VERSION < 105000 && __cplusplus < 201103L // Test missing before Boost 1.50, so before then guess based on what the compiler claims. # define BOOST_NO_CXX11_HDR_FUNCTIONAL #endif #ifndef BOOST_NO_CXX11_HDR_FUNCTIONAL # include #endif namespace { int f(int x, int y) { return x + y; } struct X { int operator()(int x, int y) { return x + y; } }; } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; boost::function free_f(&f); X x; boost::function f_obj(x); module(L) [ def("f", free_f), def("xf", f_obj) ]; DOSTRING(L, "function test(f)\n" " assert(f(0, 4) == 4)\n" " assert(f(1, 8) == 9)\n" " assert(f(5, 5) == 10)\n" "end\n" ); DOSTRING(L, "test(f)"); DOSTRING(L, "test(xf)"); #ifndef BOOST_NO_CXX11_HDR_FUNCTIONAL std::function free_f2(&f); std::function f_obj2(x); module(L) [ def("f2", free_f2), def("xf2", f_obj2) ]; DOSTRING(L, "test(f2)"); DOSTRING(L, "test(xf2)"); #endif } luabind-1.1.1/test/test_function_overload_overflow.cpp000066400000000000000000000022031366245310300233150ustar00rootroot00000000000000// Copyright Christian Neumüller 2015. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include namespace { void f() { } } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ // 11 functions def("f", &f), // 1 def("f", &f), // 2 def("f", &f), // 3 def("f", &f), // 4 def("f", &f), // 5 def("f", &f), // 6 def("f", &f), // 7 def("f", &f), // 8 def("f", &f), // 9 def("f", &f), // 10 def("f", &f) // 11 ]; DOSTRING_EXPECTED(L, "f()", "Ambiguous, candidates:\n" // 11 candidates "void f()\n" // 1 "void f()\n" // 2 "void f()\n" // 3 "void f()\n" // 4 "void f()\n" // 5 "void f()\n" // 6 "void f()\n" // 7 "void f()\n" // 8 "void f()\n" // 9 "void f()\n" // 10 "and 1 additional overload(s) not shown"); // 11 } luabind-1.1.1/test/test_has_get_pointer.cpp000066400000000000000000000036701366245310300210350ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin // 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. #include #include #include #include #include namespace lb = luabind::detail; namespace test { struct X { }; struct Y { }; Y* get_pointer(Y const&); struct Z : boost::enable_shared_from_this {}; } // namespace test #ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP namespace luabind { using test::get_pointer; using boost::get_pointer; } // namespace luabind #endif BOOST_MPL_ASSERT(( lb::has_get_pointer > )); BOOST_MPL_ASSERT(( lb::has_get_pointer )); BOOST_MPL_ASSERT(( lb::has_get_pointer )); BOOST_MPL_ASSERT_NOT(( lb::has_get_pointer )); BOOST_MPL_ASSERT_NOT(( lb::has_get_pointer )); BOOST_MPL_ASSERT(( lb::has_get_pointer )); luabind-1.1.1/test/test_headercompile.cpp.in000066400000000000000000000001121366245310300210550ustar00rootroot00000000000000#define LUABIND_TEST_HEADERCOMPILE #include "@FULLHEADER@" int main() { } luabind-1.1.1/test/test_held_type.cpp000066400000000000000000000117471366245310300176440ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include #include #include #include namespace luabind { #ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP template T* get_pointer(boost::shared_ptr const& p) { return p.get(); } #endif } namespace { struct base : counted_type { base(): n(4) {} virtual ~base() {} base(base const& rhs): n(rhs.n) {} void f(int) { } int n; }; // this is here to make sure the pointer offsetting works struct first_base : counted_type { virtual ~first_base() {} first_base(): padding(0xdead) {} first_base(first_base const& rhs): padding(rhs.padding) {} virtual void a() {} int padding; }; struct derived : first_base, base { derived(): n2(7) {} void f() {} int n2; }; COUNTER_GUARD(first_base); COUNTER_GUARD(base); int feedback = 0; void tester(base* t) { if (t->n == 4) feedback = 1; } void tester_(derived* t) { if (t->n2 == 7) feedback = 2; } void tester2(boost::shared_ptr t) { if (t->n == 4) feedback = 3; } void tester3(boost::shared_ptr t) { if (t->n == 4) feedback = 4; } void tester4(const boost::shared_ptr& t) { if (t->n == 4) feedback = 5; } void tester5(const boost::shared_ptr* t) { if ((*t)->n == 4) feedback = 6; } void tester6(const boost::shared_ptr* t) { if ((*t)->n == 4) feedback = 7; } void tester7(boost::shared_ptr* t) { if ((*t)->n == 4) feedback = 8; } boost::shared_ptr tester9() { feedback = 9; return boost::shared_ptr(new base()); } void tester10(boost::shared_ptr const& r) { if (r->n == 4) feedback = 10; } void tester11(boost::shared_ptr const& r) { if (r->n == 4) feedback = 11; } void tester12(boost::shared_ptr const& r) { if (r->n2 == 7) feedback = 12; } derived tester13() { feedback = 13; derived d; d.n2 = 13; return d; } } // namespace unnamed void test_main(lua_State* L) { boost::shared_ptr base_ptr(new base()); using namespace luabind; module(L) [ def("tester", &tester), def("tester", &tester_), def("tester2", &tester2), def("tester3", &tester3), def("tester4", &tester4), def("tester5", &tester5), def("tester6", &tester6), def("tester7", &tester7), def("tester9", &tester9), def("tester10", &tester10), def("tester11", &tester11), def("tester12", &tester12), def("tester13", &tester13), class_ >("base") .def(constructor<>()) .def("f", &base::f), class_ >("derived") .def(constructor<>()) .def("f", &derived::f) ]; object g = globals(L); g["ptr"] = base_ptr; DOSTRING(L, "tester(ptr)"); TEST_CHECK(feedback == 1); DOSTRING(L, "a = base()\n" "b = derived()\n"); #if LUABIND_VERSION != 900 DOSTRING(L, "tester(b)"); TEST_CHECK(feedback == 2); #endif DOSTRING(L, "tester(a)"); TEST_CHECK(feedback == 1); DOSTRING(L, "tester2(b)"); TEST_CHECK(feedback == 3); feedback = 0; DOSTRING(L, "tester10(b)"); TEST_CHECK(feedback == 10); /* this test is messed up, shared_ptr isn't even registered DOSTRING_EXPECTED( L , "tester12(b)" , "no match for function call 'tester12' with the parameters (derived)\n" "candidates are:\n" "tester12(const custom&)\n"); */ #if LUABIND_VERSION != 900 object nil = globals(L)["non_existing_variable_is_nil"]; TEST_CHECK(object_cast >(nil).get() == 0); TEST_CHECK(object_cast >(nil).get() == 0); #endif DOSTRING(L, "tester13()"); TEST_CHECK(feedback == 13); } luabind-1.1.1/test/test_implicit_cast.cpp000066400000000000000000000071121366245310300205020ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include #include namespace { struct A : counted_type { virtual ~A() {} }; struct B : A, counted_type {}; struct enum_placeholder {}; typedef enum { VAL1 = 1, VAL2 = 2 } LBENUM_t; LBENUM_t enum_by_val(LBENUM_t e) { return e; } LBENUM_t enum_by_const_ref(const LBENUM_t &e) { return e; } struct test_implicit : counted_type { char const* f(A*) { return "f(A*)"; } char const* f(B*) { return "f(B*)"; } }; void not_convertable(boost::shared_ptr) { TEST_ERROR("not_convertable(boost::shared_ptr) should not be called"); } int f(int& a) { return a; } COUNTER_GUARD(A); COUNTER_GUARD(B); COUNTER_GUARD(test_implicit); } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; typedef char const*(test_implicit::*f1)(A*); typedef char const*(test_implicit::*f2)(B*); module(L) [ class_("A") .def(constructor<>()), class_("B") .def(constructor<>()), class_("test") .def(constructor<>()) .def("f", static_cast(&test_implicit::f)) .def("f", static_cast(&test_implicit::f)), class_("LBENUM") .enum_("constants") [ value("VAL1", VAL1), value("VAL2", VAL2) ], def("enum_by_val", &enum_by_val), def("enum_by_const_ref", &enum_by_const_ref), def("no_convert", ¬_convertable), def("f", &f) ]; DOSTRING(L, "a = A()"); DOSTRING(L, "b = B()"); DOSTRING(L, "t = test()"); DOSTRING(L, "assert(t:f(a) == 'f(A*)')"); DOSTRING(L, "assert(t:f(b) == 'f(B*)')"); DOSTRING(L, "assert(LBENUM.VAL1 == 1)"); DOSTRING(L, "assert(LBENUM.VAL2 == 2)"); DOSTRING(L, "assert(enum_by_val(LBENUM.VAL1) == LBENUM.VAL1)"); DOSTRING(L, "assert(enum_by_val(LBENUM.VAL2) == LBENUM.VAL2)"); DOSTRING(L, "assert(enum_by_const_ref(LBENUM.VAL1) == LBENUM.VAL1)"); DOSTRING(L, "assert(enum_by_const_ref(LBENUM.VAL2) == LBENUM.VAL2)"); DOSTRING_EXPECTED(L, "a = A()\n" "no_convert(a)", ("No matching overload found, candidates:\n" "void no_convert(custom [" + type_id(typeid(boost::shared_ptr)).name() + "])").c_str()); DOSTRING_EXPECTED(L, "a = nil\n" "f(a)", "No matching overload found, candidates:\n" "int f(int&)"); } luabind-1.1.1/test/test_implicit_raw.cpp000066400000000000000000000011541366245310300203410ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include static void raw_function(lua_State*) {} static void raw_function2(int, lua_State*, int) {} void test_main(lua_State* L) { using namespace luabind; module(L) [ def("raw_function", &raw_function), def("raw_function2", &raw_function2) ]; DOSTRING(L, "raw_function()\n" "raw_function2(1,2)\n" ); } luabind-1.1.1/test/test_intrusive_ptr.cpp000066400000000000000000000043461366245310300206010ustar00rootroot00000000000000// Copyright Chsritian Neumüller 2013. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include #include #include #include using boost::intrusive_ptr; namespace { struct B: private boost::noncopyable, counted_type { B(int val_): ref_cnt(0), val(val_) {} virtual ~B() { std::cout << "~B\n"; TEST_CHECK(ref_cnt == 0); } int ref_cnt; int val; }; COUNTER_GUARD(B); struct D: B { D(int val_): B(val_) {} }; void intrusive_ptr_add_ref(B* b) { ++b->ref_cnt; } void intrusive_ptr_release(B* b) { if (!--b->ref_cnt) delete b; } void needs_b(intrusive_ptr pb, int expected_rc) { TEST_CHECK(pb->ref_cnt == expected_rc); } void needs_d(intrusive_ptr pd) { TEST_CHECK(pd->ref_cnt == 2); } intrusive_ptr filter_b(intrusive_ptr pb) { TEST_CHECK(pb->ref_cnt == 2); return pb; } } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_ >("B") .def(constructor()) .def_readonly("val", &B::val) .def_readonly("ref_cnt", &B::ref_cnt), class_ >("D") .def(constructor()), def("needs_b", &needs_b), def("needs_d", &needs_d), def("filter_b", &filter_b) ]; DOSTRING(L, "d = D(1)\n" "print(d.val, d.ref_cnt)\n" "assert(d.val == 1)\n" "assert(d.ref_cnt == 1)\n" ); DOSTRING(L, "needs_d(d)\n" "needs_b(d, 2)\n" ); DOSTRING(L, "bd = filter_b(d)\n" "assert(bd.val == 1)\n" "assert(bd.ref_cnt == 2)\n" "needs_b(bd, 3)\n" "assert(bd.ref_cnt == 2)\n" ); DOSTRING(L, "d = nil\n" "collectgarbage()\n" "collectgarbage()\n" "assert(bd.ref_cnt == 1)\n" ); } luabind-1.1.1/test/test_iterator.cpp000066400000000000000000000031121366245310300175030ustar00rootroot00000000000000// Copyright Daniel Wallin 2007. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include #include #include struct container { container() { for (int i = 0; i < 5; ++i) data[i] = i + 1; } struct iterator : boost::iterator_adaptor { static std::size_t alive; iterator(int* p) : iterator::iterator_adaptor_(p) { ++alive; } iterator(iterator const& other) : iterator::iterator_adaptor_(other) { ++alive; } ~iterator() { --alive; } }; iterator begin() { return iterator(data); } iterator end() { return iterator(data + 5); } int data[5]; }; std::size_t container::iterator::alive = 0; struct cls { container iterable; }; void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("cls") .def(constructor<>()) .def_readonly("iterable", &cls::iterable, return_stl_iterator) ]; DOSTRING(L, "x = cls()\n" "sum = 0\n" "for i in x.iterable do\n" " sum = sum + i\n" "end\n" "assert(sum == 15)\n" "collectgarbage('collect')\n" ); assert(container::iterator::alive == 0); } luabind-1.1.1/test/test_lua_classes.cpp000066400000000000000000000244061366245310300201610ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin, Arvid Norberg // 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. #include "test.hpp" #include #include #include #include namespace luabind { #ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP template T* get_pointer(boost::shared_ptr const& p) { return p.get(); } #endif } using namespace luabind; namespace { struct A : counted_type { virtual ~A() {} virtual std::string f() { return "A:f()"; } virtual std::string g() const { return "A:g()"; } }; struct A_wrap : A, wrap_base { std::string f() { return call_member(this, "f"); } static std::string default_f(A* p) { return p->A::f(); } std::string g() const { return call_member(this, "g"); } static std::string default_g(A const* p) { return p->A::g(); } }; struct B : A { virtual std::string f() { return "B:f()"; } }; struct B_wrap : B, wrap_base { virtual std::string f() { return call_member(this, "f"); } static std::string default_f(B* p) { return p->B::f(); } virtual std::string g() const { return call_member(this, "g"); } static std::string default_g(B const* p) { return p->B::g(); } }; struct base : counted_type { virtual ~base() {} virtual std::string f() { return "base:f()"; } virtual std::string g() const { return ""; } }; base* filter(base* p) { return p; } struct base_wrap : base, wrap_base { virtual std::string f() { return call_member(this, "f"); } static std::string default_f(base* p) { return p->base::f(); } virtual std::string g() const { return call_member(this, "g"); } }; struct T_ // vc6.5, don't name your types T! { int f(int) { return 1; } }; struct U : T_ { int g() { return 3; } int f(int, int) { return 2; } }; } // namespace unnamed void test_main(lua_State* L) { module(L) [ class_ >("A") .def(constructor<>()) .def("f", &A::f, &A_wrap::default_f) .def("g", &A::g, &A_wrap::default_g), class_ >("B") .def(constructor<>()) .def("f", &B::f, &B_wrap::default_f) .def("g", &B::g, &B_wrap::default_g), def("filter", &filter), class_("base") .def(constructor<>()) .def("f", &base::f, &base_wrap::default_f) .def("g", &base::g), class_("T") .def("f", &T_::f), class_("U") .def(constructor<>()) .def("f", &T_::f) .def("f", &U::f) .def("g", &U::g) ]; DOSTRING(L, "u = U()\n" "assert(u:f(0) == 1)\n" "assert(u:f(0,0) == 2)\n" "assert(u:g() == 3)\n"); DOSTRING(L, "u = U()\n" "assert(u:f(0) == 1)\n" "assert(u:f(0,0) == 2)\n" "assert(u:g() == 3)\n"); DOSTRING(L, "function base:fun()\n" " return 4\n" "end\n" "ba = base()\n" "assert(ba:fun() == 4)"); DOSTRING(L, "function base:gen_member_error()\n" " assert(0 == 1)\n" "end\n" "provide_member_error = base()\n"); DOSTRING(L, "class 'derived' (base)\n" " function derived:__init() base.__init(self) end\n" " function derived:f()\n" " return 'derived:f() : ' .. base.f(self)\n" " end\n" "class 'empty_derived' (base)\n" " function empty_derived:__init() base.__init(self) end\n" "class 'C' (B)\n" " function C:__init() B.__init(self) end\n" " function C:f() return 'C:f()' end\n" "function make_derived()\n" " return derived()\n" "end\n" "function make_empty_derived()\n" " return empty_derived()\n" "end\n" "function adopt_ptr(x)\n" " a = x\n" "end\n"); DOSTRING(L, "function gen_error()\n" " assert(0 == 1)\n" "end\n"); DOSTRING(L, "a = A()\n" "b = B()\n" "c = C()\n" "assert(c:f() == 'C:f()')\n" "assert(b:f() == 'B:f()')\n" "assert(a:f() == 'A:f()')\n" "assert(b:g() == 'A:g()')\n" "assert(c:g() == 'A:g()')\n" "assert(C.f(c) == 'C:f()')\n" "assert(B.f(c) == 'B:f()')\n" "assert(A.f(c) == 'A:f()')\n" "assert(A.g(c) == 'A:g()')\n"); #ifndef LUABIND_NO_EXCEPTONS { LUABIND_CHECK_STACK(L); try { call_function(L, "gen_error"); } catch (luabind::error&) { bool result( lua_tostring(L, -1) == std::string("[string \"function " "gen_error()...\"]:2: assertion failed!")); TEST_CHECK(result); lua_pop(L, 1); } } { A a; DOSTRING(L, "function test_ref(x) end"); call_function(L, "test_ref", boost::ref(a)); } { LUABIND_CHECK_STACK(L); try { call_function(L, "gen_error"); } catch (luabind::error&) { bool result( lua_tostring(L, -1) == std::string("[string \"function " "gen_error()...\"]:2: assertion failed!")); TEST_CHECK(result); lua_pop(L, 1); } } { LUABIND_CHECK_STACK(L); try { call_function(L, "gen_error") [ adopt(result) ]; } catch (luabind::error&) { bool result( lua_tostring(L, -1) == std::string("[string \"function " "gen_error()...\"]:2: assertion failed!")); TEST_CHECK(result); lua_pop(L, 1); } } { LUABIND_CHECK_STACK(L); object provide_member_error = globals(L)["provide_member_error"]; try { call_member(provide_member_error, "gen_member_error"); } catch (luabind::error&) { bool result( lua_tostring(L, -1) == std::string("[string \"function " "base:gen_member_error()...\"]:2: assertion failed!")); TEST_CHECK(result); lua_pop(L, 1); } } { LUABIND_CHECK_STACK(L); object provide_member_error = globals(L)["provide_member_error"]; try { call_member(provide_member_error, "gen_member_error"); } catch (luabind::error&) { bool result( lua_tostring(L, -1) == std::string("[string \"function " "base:gen_member_error()...\"]:2: assertion failed!")); TEST_CHECK(result); lua_pop(L, 1); } } #endif base* ptr = 0; { LUABIND_CHECK_STACK(L); TEST_NOTHROW( object a = globals(L)["ba"]; TEST_CHECK(call_member(a, "fun") == 4); ); } { LUABIND_CHECK_STACK(L); object make_derived = globals(L)["make_derived"]; TEST_NOTHROW( call_function(make_derived) ); } #ifdef LUABIND_USE_CXX11 std::unique_ptr own_ptr; #else std::auto_ptr own_ptr; #endif { LUABIND_CHECK_STACK(L); #ifdef LUABIND_USE_CXX11 TEST_NOTHROW( own_ptr = std::unique_ptr( call_function(L, "make_derived") [ adopt(result) ]) ); #else TEST_NOTHROW( own_ptr = std::auto_ptr( call_function(L, "make_derived") [ adopt(result) ]) ); #endif } // make sure the derived lua-part is still referenced by // the adopted c++ pointer DOSTRING(L, "collectgarbage()\n" "collectgarbage()\n" "collectgarbage()\n" "collectgarbage()\n" "collectgarbage()\n"); TEST_NOTHROW( TEST_CHECK(own_ptr->f() == "derived:f() : base:f()") ); #ifdef LUABIND_USE_CXX11 own_ptr = std::unique_ptr(); #else own_ptr = std::auto_ptr(); #endif // test virtual functions that are not overridden by lua #ifdef LUABIND_USE_CXX11 TEST_NOTHROW( own_ptr = std::unique_ptr( call_function(L, "make_empty_derived") [ adopt(result) ]) ); #else TEST_NOTHROW( own_ptr = std::auto_ptr( call_function(L, "make_empty_derived") [ adopt(result) ]) ); #endif TEST_NOTHROW( TEST_CHECK(own_ptr->f() == "base:f()") ); TEST_NOTHROW( call_function(L, "adopt_ptr", own_ptr.get()) [ adopt(_1) ] ); own_ptr.release(); // test virtual functions that are overridden by lua TEST_NOTHROW( ptr = call_function(L, "derived") ); if (ptr) { TEST_NOTHROW( TEST_CHECK(ptr->f() == "derived:f() : base:f()") ); } // test virtual function dispatch from within lua DOSTRING(L, "a = derived()\n" "b = filter(a)\n" "assert(b:f() == 'derived:f() : base:f()')\n"); // test back references DOSTRING(L, "a = derived()\n" "assert(a == filter(a))\n"); } luabind-1.1.1/test/test_null_pointer.cpp000066400000000000000000000033001366245310300203630ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include namespace { struct A : counted_type { A* f() { return 0; } }; A* return_pointer() { return 0; } COUNTER_GUARD(A); } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("A") .def(constructor<>()) .def("f", &A::f), def("return_pointer", &return_pointer) ]; DOSTRING(L, "e = return_pointer()\n" "assert(e == nil)"); DOSTRING(L, "a = A()\n" "e = a:f()\n" "assert(e == nil)"); } luabind-1.1.1/test/test_object.cpp000066400000000000000000000274751366245310300171420ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include #include #include #include #include #include #include using namespace luabind; namespace { int test_object_param(const object& table) { LUABIND_CHECK_STACK(table.interpreter()); object current_object; current_object = table; lua_State* L = table.interpreter(); if (type(table) == LUA_TTABLE) { int sum1 = 0; for (iterator i(table), e; i != e; ++i) { assert(type(*i) == LUA_TNUMBER); sum1 += object_cast(*i); } int sum2 = 0; for (raw_iterator i(table), e; i != e; ++i) { assert(type(*i) == LUA_TNUMBER); sum2 += object_cast(*i); } // test iteration of empty table object empty_table = newtable(L); for (iterator i(empty_table), e; i != e; ++i) {} table["sum1"] = sum1; table["sum2"] = sum2; table["blurp"] = 5; table["sum3"] = table["sum1"]; return 0; } else { if (type(table) != LUA_TNIL) { return 1; } else { return 2; } } } int test_fun() { return 42; } struct test_param : counted_type { luabind::object obj; luabind::object obj2; bool operator==(test_param const& rhs) const { return obj == rhs.obj && obj2 == rhs.obj2; } }; COUNTER_GUARD(test_param); int test_match(const luabind::object&) { return 0; } int test_match(int) { return 1; } void test_match_object( luabind::object p1 , luabind::object p2 , luabind::object p3) { p1["ret"] = 1; p2["ret"] = 2; p3["ret"] = 3; } void test_call(lua_State* L) { DOSTRING(L, "function sum(...)\n" " local result = 0\n" " for _,x in pairs({...}) do\n" " result = result + x\n" " end\n" " return result\n" "end\n" ); object sum = globals(L)["sum"]; TEST_CHECK(object_cast(sum()) == 0); TEST_CHECK(object_cast(sum(1)) == 1); TEST_CHECK(object_cast(sum(1,2)) == 3); TEST_CHECK(object_cast(sum(1,2,3)) == 6); TEST_CHECK(object_cast(sum(1,2,3,4)) == 10); TEST_CHECK(object_cast(sum(1,2,3,4,5)) == 15); } void test_metatable(lua_State* L) { object metatable = newtable(L); object G = globals(L); DOSTRING(L, "function index_function(table, key)\n" " return key*2\n" "end\n" "index_table = {}" ); metatable["__index"] = G["index_function"]; setmetatable(G["index_table"], metatable); DOSTRING(L, "assert(index_table[0] == 0)\n" "assert(index_table[1] == 2)\n" "assert(index_table[2] == 4)\n" ); DOSTRING(L, "setmetatable(index_table, { ['luabind.metatable'] = 1 })" ); assert(getmetatable(G["index_table"])["luabind.metatable"] == 1); assert(type(getmetatable(G["index_table"])["nonexistent"]) == LUA_TNIL); } int with_upvalues(lua_State *) { return 0; } void test_upvalues(lua_State* L) { lua_pushnumber(L, 3); lua_pushnumber(L, 4); lua_pushcclosure(L, &with_upvalues, 2); object f(from_stack(L, -1)); lua_pop(L, 1); assert(getupvalue(f, 1) == 3); assert(getupvalue(f, 2) == 4); setupvalue(f, 1, object(L, 4)); assert(getupvalue(f, 1) == 4); assert(getupvalue(f, 2) == 4); setupvalue(f, 2, object(L, 5)); assert(getupvalue(f, 1) == 4); assert(getupvalue(f, 2) == 5); } void test_explicit_conversions(lua_State* L) { lua_pushcclosure(L, &with_upvalues, 0); object f(from_stack(L, -1)); lua_pop(L, 1); assert(tocfunction(f) == &with_upvalues); int* p = static_cast(lua_newuserdata(L, sizeof(int))); *p = 1234; object x(from_stack(L, -1)); lua_pop(L, 1); assert(*touserdata(x) == 1234); } int with_argument(argument const& arg) { return object_cast(arg) * 2; } int with_table_argument(argument const& arg, argument const& key) { return object_cast(arg[key]); } void test_argument(lua_State* L) { module(L) [ def("with_argument", &with_argument), def("with_table_argument", &with_table_argument) ]; DOSTRING(L, "assert(with_argument(1) == 2)\n" "assert(with_argument(2) == 4)\n" ); DOSTRING(L, "x = { foo = 1, bar = 2 }\n" "assert(with_table_argument(x, 'foo') == 1)\n" "assert(with_table_argument(x, 'bar') == 2)\n" ); } void test_bool_convertible(lua_State* L) { DOSTRING(L, "x1 = nil\n" "x2 = false\n" "x3 = 0\n" "x4 = 1\n" ); DOSTRING(L, "assert(not x1)\n" "assert(not x2)\n" "assert(x3)\n" "assert(x4)\n" ); object G = globals(L); object x1 = G["x1"]; object x2 = G["x2"]; object x3 = G["x3"]; object x4 = G["x4"]; assert(!x1); assert(!x2); assert(x3); assert(x4); assert(!G["x1"]); assert(!G["x2"]); assert(G["x3"]); assert(G["x4"]); } } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ def("test_object_param", &test_object_param), def("test_fun", &test_fun), def("test_match", static_cast(&test_match)), def("test_match", static_cast(&test_match)), def("test_match_object", &test_match_object), class_("test_param") .def(constructor<>()) .def_readwrite("obj", &test_param::obj) .def_readonly("obj2", &test_param::obj2) .def(const_self == const_self) ]; object uninitialized; TEST_CHECK(!uninitialized); TEST_CHECK(!uninitialized.is_valid()); test_param temp_object; globals(L)["temp"] = temp_object; TEST_CHECK(object_cast(globals(L)["temp"]) == temp_object); globals(L)["temp"] = &temp_object; TEST_CHECK(object_cast(globals(L)["temp"]) == &temp_object); TEST_CHECK(globals(L)["temp"] == temp_object); // test the registry object reg = registry(L); reg["__a"] = "foobar"; TEST_CHECK(object_cast(registry(L)["__a"]) == "foobar"); DOSTRING(L, "t = 2\n" "assert(test_object_param(t) == 1)"); DOSTRING(L, "assert(test_object_param(nil) == 2)"); DOSTRING(L, "t = { ['oh'] = 4, 3, 5, 7, 13 }"); DOSTRING(L, "assert(test_object_param(t) == 0)"); DOSTRING(L, "assert(t.sum1 == 4 + 3 + 5 + 7 + 13)"); DOSTRING(L, "assert(t.sum2 == 4 + 3 + 5 + 7 + 13)"); DOSTRING(L, "assert(t.blurp == 5)"); object g = globals(L); object ret = g["test_fun"](); TEST_CHECK(object_cast(ret) == 42); DOSTRING(L, "function test_param_policies(x, y) end"); object test_param_policies = g["test_param_policies"]; int a = type(test_param_policies); TEST_CHECK(a == LUA_TFUNCTION); luabind::object obj; obj = luabind::object(); // call the function and tell lua to adopt the pointer passed as first argument test_param_policies(5, new test_param())[adopt(_2)]; DOSTRING(L, "assert(test_match(7) == 1)"); DOSTRING(L, "assert(test_match('oo') == 0)"); DOSTRING(L, "t = test_param()\n" "t.obj = 'foo'\n" "assert(t.obj == 'foo')\n" "assert(t.obj2 == nil)"); DOSTRING(L, "function test_object_policies(a) glob = a\n" "return 6\n" "end"); object test_object_policies = g["test_object_policies"]; object ret_val = test_object_policies("teststring")[detail::null_type()]; TEST_CHECK(object_cast(ret_val) == 6); TEST_CHECK(ret_val == 6); TEST_CHECK(6 == ret_val); g["temp_val"] = 6; TEST_CHECK(ret_val == g["temp_val"]); object temp_val = g["temp_val"]; TEST_CHECK(ret_val == temp_val); g["temp"] = "test string"; TEST_CHECK(boost::lexical_cast(g["temp"]) == "test string"); g["temp"] = 6; TEST_CHECK(boost::lexical_cast(g["temp"]) == "6"); TEST_CHECK(object_cast(g["glob"]) == "teststring"); TEST_CHECK(object_cast(gettable(g, "glob")) == "teststring"); TEST_CHECK(object_cast(rawget(g, "glob")) == "teststring"); object t = newtable(L); TEST_CHECK(iterator(t) == iterator()); TEST_CHECK(raw_iterator(t) == raw_iterator()); t["foo"] = "bar"; TEST_CHECK(object_cast(t["foo"]) == "bar"); TEST_CHECK(object_cast(*iterator(t)) == "bar"); TEST_CHECK(object_cast(*raw_iterator(t)) == "bar"); t["foo"] = nil; // luabind::nil_type TEST_CHECK(iterator(t) == iterator()); TEST_CHECK(raw_iterator(t) == raw_iterator()); t["foo"] = "bar"; iterator it1(t); *it1 = nil; TEST_CHECK(iterator(t) == iterator()); TEST_CHECK(raw_iterator(t) == raw_iterator()); t["foo"] = "bar"; raw_iterator it2(t); *it2 = nil; TEST_CHECK(iterator(t) == iterator()); TEST_CHECK(raw_iterator(t) == raw_iterator()); DOSTRING(L, "p1 = {}\n" "p2 = {}\n" "p3 = {}\n" "test_match_object(p1, p2, p3)\n" "assert(p1.ret == 1)\n" "assert(p2.ret == 2)\n" "assert(p3.ret == 3)\n"); #ifndef LUABIND_NO_EXCEPTIONS try { object not_initialized; int i = object_cast(not_initialized); (void)i; TEST_ERROR("invalid cast succeeded"); } catch(luabind::cast_failed&) {} #endif object not_initialized; TEST_CHECK(!object_cast_nothrow(not_initialized)); TEST_CHECK(!not_initialized.is_valid()); TEST_CHECK(!not_initialized); DOSTRING(L, "t = { {1}, {2}, {3}, {4} }"); int inner_sum = 0; for (iterator i(globals(L)["t"]), e; i != e; ++i) { inner_sum += object_cast((*i)[1]); } TEST_CHECK(inner_sum == 1 + 2 + 3 + 4); DOSTRING(L, "t = { {1, 2}, {3, 4}, {5, 6}, {7, 8} }"); inner_sum = 0; for (iterator i(globals(L)["t"]), e; i != e; ++i) { for (iterator j(*i), e2; j != e2; ++j) { inner_sum += object_cast(*j); } } TEST_CHECK(inner_sum == 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8); TEST_CHECK(object_cast(globals(L)["t"][2][2]) == 4); DOSTRING(L, "obj = setmetatable({}, {\n" " __tostring = function() return 'custom __tostring' end})"); TEST_CHECK( boost::lexical_cast(globals(L)["obj"]) == "custom __tostring"); test_call(L); test_metatable(L); test_upvalues(L); test_explicit_conversions(L); test_argument(L); test_bool_convertible(L); } luabind-1.1.1/test/test_operators.cpp000066400000000000000000000153561366245310300177050ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include #include #include namespace { struct operator_tester : counted_type { int operator+(int a) const { return 1 + a; } int operator-() const { return 46; } float operator()() const { return 3.5f; } float operator()(int a) const { return 3.5f + a; } float operator()(int a) { return 2.5f + a; } }; float operator*(operator_tester const& /*lhs*/, operator_tester const& /*rhs*/) { return 35.f; } float operator%(operator_tester const& /*lhs*/, operator_tester const& /*rhs*/) { return 15.f; } std::string operator*(operator_tester const&, int) { return "(operator_tester, int) overload"; } int operator+(int a, const operator_tester&) { return 2 + a; } struct operator_tester2 : counted_type { }; int operator+(const operator_tester&, const operator_tester2&) { return 73; } struct operator_tester3: operator_tester, counted_type {}; std::ostream& operator<<(std::ostream& os, const operator_tester&) { os << "operator_tester"; return os; } struct op_test1 { bool operator==(op_test1 const& /*rhs*/) const { return true; } }; struct op_test2 : public op_test1 { bool operator==(op_test2 const& /*rhs*/) const { return true; } }; COUNTER_GUARD(operator_tester); COUNTER_GUARD(operator_tester2); COUNTER_GUARD(operator_tester3); struct len_tester { len_tester(int len_) : m_len(len_) {} int len() const { return m_len; } int m_len; }; struct B {}; struct D: B {}; struct nameless {}; nameless make_nameless() { return nameless(); } } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("operator_tester") .def(constructor<>()) .def(tostring(const_self)) .def(self + int()) .def(other() + self) .def(-self) .def(self + other()) .def(self()) .def(const_self(int())) .def(self(int())) // .def(const_self * other()) .def(const_self * const_self) .def(const_self * other()) .def(const_self % const_self) // .def("clone", &clone, adopt(return_value)), , class_("operator_tester2") .def(constructor<>()) .def(other() + self), class_("operator_tester3") .def(constructor<>()), class_("op_test1") .def(constructor<>()) .def(const_self == const_self), class_("op_test2") .def(constructor<>()) .def(self == self), class_("len_tester") .def(constructor()) .def("__len", &len_tester::len), class_(), def("make_nameless", &make_nameless), class_("B") .def(constructor<>()), class_("D") .def(constructor<>()) ]; DOSTRING(L, "test = operator_tester()"); DOSTRING(L, "test2 = operator_tester2()"); DOSTRING(L, "test3 = operator_tester3()"); DOSTRING(L, "assert(tostring(test) == 'operator_tester')"); DOSTRING(L, "assert(test() == 3.5)"); DOSTRING(L, "assert(test(5) == 2.5 + 5)"); DOSTRING(L, "assert(-test == 46)"); DOSTRING(L, "assert(test * test == 35)"); DOSTRING(L, "assert(test % test == 15)"); DOSTRING(L, "assert(test * 3 == '(operator_tester, int) overload')") DOSTRING(L, "assert(test + test2 == 73)"); DOSTRING(L, "assert(2 + test == 2 + 2)"); DOSTRING(L, "assert(test + 2 == 1 + 2)"); DOSTRING(L, "assert(test3 + 6 == 1 + 6)"); DOSTRING(L, "assert(test3 + test2 == 73)"); DOSTRING(L, "assert(tostring(test) == 'operator_tester')"); // Default __tostring should be "class NAME: ADDRESS". DOSTRING(L, "assert(tostring(test2):match('" // Pointer representation is platform dependent, don't check it. "^operator_tester2 object: " "'))"); DOSTRING(L, "print(test2)"); DOSTRING(L, "print(make_nameless())"); DOSTRING_EXPECTED(L, "local d = test2 / test3", "class operator_tester2: no __div operator defined."); const char* prog = "class 'my_class'\n" "function my_class:__add(lhs)\n" " return my_class(self.val + lhs.val)\n" "end\n" "function my_class:__init(a)\n" " self.val = a\n" "end\n" "function my_class:__sub(v)\n" " if (type(self) == 'number') then\n" " return my_class(self - v.val)\n" " elseif (type(v) == 'number') then\n" " return my_class(self.val - v)\n" " else\n" " return my_class(self.val - v.val)\n" " end\n" "end\n" "a = my_class(3)\n" "b = my_class(7)\n" "c = a + b\n" "d = a - 2\n" "d = 10 - d\n" "d = d - b\n"; DOSTRING(L, prog); DOSTRING(L, "assert(c.val == 10)"); DOSTRING(L, "assert(d.val == 2)"); DOSTRING(L, "a = op_test1()\n" "b = op_test2()\n" "assert(a == b)"); DOSTRING(L, "x = len_tester(0)\n"); DOSTRING(L, "x = len_tester(3)\n" "assert(#x == 3)"); D d; globals(L)["d"] = &d; globals(L)["b"] = static_cast(&d); DOSTRING(L, "assert(d == b)\n" "assert(b == d)\n" "assert(d ~= x)\n"); } luabind-1.1.1/test/test_out_value.cpp000066400000000000000000000007221366245310300176610ustar00rootroot00000000000000// Currently fails to compile (See // https://github.com/Oberon00/luabind/issues/30) #include "test.hpp" #include #include void f(float& val) { val = val + 10.f; } void test_main(lua_State* L) { using namespace luabind; module(L) [ def("f", &f, out_value(_1)) // compiles with "pure_out_value" ]; // out_value DOSTRING(L, "a = f(5)\n" "assert(a == 15)"); } luabind-1.1.1/test/test_package_preload.cpp000066400000000000000000000051501366245310300207570ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // Copyright (c) 2012 Iowa State University // 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. #include "test.hpp" #include #include #include static int f(int x) { return x + 1; } static void loader(lua_State* L, char const* modname) { TEST_CHECK(modname); TEST_CHECK(modname && std::strcmp(modname, "testmod") == 0); using namespace luabind; module(L) [ def("f", &f) ]; } static luabind::object local_loader(lua_State* L, char const* modname) { TEST_CHECK(modname); TEST_CHECK(modname && std::strcmp(modname, "testmod_l") == 0); using namespace luabind; object modtable = newtable(L); module(modtable) [ def("f", &f) ]; return modtable; } void test_main(lua_State* L) { using namespace luabind; set_package_preload(L, "testmod", &loader); DOSTRING(L, "assert(require('testmod') == true)"); DOSTRING(L, "assert(f(7) == 8)"); set_package_preload(L, "testmod_l", &local_loader); DOSTRING(L, "mod = require('testmod_l')"); DOSTRING(L, "assert(not testmod_l)\n" // No global should be created. "assert(mod.f(41) == 42)\n"); // Module should be returned. DOSTRING(L, "package.preload = nil"); try { set_package_preload(L, "failmod", &loader); } catch (luabind::error const&) { TEST_CHECK(std::strcmp("attempt to index a nil value", lua_tostring(L, -1)) == 0); lua_pop(L, 1); return; } TEST_ERROR("set_package_preload() should have thrown."); } luabind-1.1.1/test/test_policies.cpp000066400000000000000000000137061366245310300174730ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include #include #include #include #include #include #include namespace { struct test_copy {}; struct secret_type {}; secret_type sec_; struct policies_test_class { policies_test_class(const char* name): name_(name) { ++count; } policies_test_class() { ++count; } ~policies_test_class() { --count; } std::string name_; policies_test_class* make(const char* name) const { return new policies_test_class(name); } void f(policies_test_class* p) { delete p; } const policies_test_class* internal_ref() { return this; } policies_test_class* self_ref() { return this; } static int count; // private: policies_test_class(policies_test_class const& c): name_(c.name_) { ++count; } void member_out_val(int a, int* v) { *v = a * 2; } secret_type* member_secret() { return &sec_; } }; int policies_test_class::count = 0; policies_test_class global; void out_val(float* f) { *f = 3.f; } policies_test_class* copy_val() { return &global; } policies_test_class const* copy_val_const() { return &global; } secret_type* secret() { return &sec_; } struct test_t { test_t *make(int) { return new test_t(); } void take(test_t*) {} }; struct MI2; struct MI1 { void add(MI2 *) {} }; struct MI2 : public MI1 { virtual ~MI2() {} }; struct MI2W : public MI2, public luabind::wrap_base {}; } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("test_t") .def("make", &test_t::make, adopt(return_value)) .def("take", &test_t::take, adopt(_2)) ]; module(L) [ class_("test") .def(constructor<>()) .def("member_out_val", &policies_test_class::member_out_val, pure_out_value(_3)) .def("member_secret", &policies_test_class::member_secret, discard_result) .def("f", &policies_test_class::f, adopt(_2)) .def("make", &policies_test_class::make, adopt(return_value)) .def("internal_ref", &policies_test_class::internal_ref, dependency(result, _1)) .def("self_ref", &policies_test_class::self_ref, return_reference_to(_1)), def("out_val", &out_val, pure_out_value(_1)), def("copy_val", ©_val, copy(result)), def("copy_val_const", ©_val_const, copy(result)), def("secret", &secret, discard_result), class_("mi1") .def(constructor<>()) .def("add",&MI1::add,adopt(_2)), class_("mi2") .def(constructor<>()) ]; // test copy DOSTRING(L, "a = secret()\n"); TEST_CHECK(policies_test_class::count == 1); DOSTRING(L, "a = copy_val()\n"); TEST_CHECK(policies_test_class::count == 2); DOSTRING(L, "b = copy_val_const()\n"); TEST_CHECK(policies_test_class::count == 3); DOSTRING(L, "a = nil\n" "b = nil\n" "collectgarbage()\n"); // only the global variable left here TEST_CHECK(policies_test_class::count == 1); // out_value DOSTRING(L, "a = out_val()\n" "assert(a == 3)"); // return_reference_to DOSTRING(L, "a = test()\n" "b = a:self_ref()\n" "a = nil\n" "collectgarbage()"); // a is kept alive as long as b is alive TEST_CHECK(policies_test_class::count == 2); DOSTRING(L, "b = nil\n" "collectgarbage()"); TEST_CHECK(policies_test_class::count == 1); DOSTRING(L, "a = test()"); TEST_CHECK(policies_test_class::count == 2); DOSTRING(L, "b = a:internal_ref()\n" "a = nil\n" "collectgarbage()"); // a is kept alive as long as b is alive TEST_CHECK(policies_test_class::count == 2); // two gc-cycles because dependency-table won't be collected in the // same cycle as the object_rep DOSTRING(L, "b = nil\n" "collectgarbage()\n" "collectgarbage()"); TEST_CHECK(policies_test_class::count == 1); // adopt DOSTRING(L, "a = test()"); TEST_CHECK(policies_test_class::count == 2); DOSTRING(L, "b = a:make('tjosan')"); DOSTRING(L, "assert(a:member_out_val(3) == 6)"); DOSTRING(L, "a:member_secret()"); // make instantiated a new policies_test_class TEST_CHECK(policies_test_class::count == 3); DOSTRING(L, "a:f(b)\n"); // b was adopted by c++ and deleted the object TEST_CHECK(policies_test_class::count == 2); DOSTRING(L, "a = nil\n" "collectgarbage()"); TEST_CHECK(policies_test_class::count == 1); // adopt with wrappers DOSTRING(L, "mi1():add(mi2())"); } luabind-1.1.1/test/test_private_destructors.cpp000066400000000000000000000042371366245310300217760ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include namespace { struct X { private: ~X() {} }; int ptr_count = 0; template struct ptr { ptr() : p(0) { ptr_count++; } ptr(T* p_) : p(p_) { ptr_count++; } ptr(ptr const& other) : p(other.p) { ptr_count++; } template ptr(ptr const& other) : p(other.p) { ptr_count++; } ~ptr() { ptr_count--; } T* p; }; template T* get_pointer(ptr const& x) { return x.p; } void f1(X const&) {} void f2(X&) {} void f3(X const*) {} void f4(X*) {} void g1(ptr p) { TEST_CHECK(ptr_count == (p.p ? 2 : 3)); } void g2(ptr const& p) { TEST_CHECK(ptr_count == (p.p ? 1 : 2)); } void g3(ptr*) { TEST_CHECK(ptr_count == 1); } void g4(ptr const*) { TEST_CHECK(ptr_count == 1); } ptr get() { return ptr(new X); } } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_ >("X"), def("get", &get), def("f1", &f1), def("f2", &f2), def("f3", &f3), def("f4", &f4), def("g1", &g1), def("g2", &g2), def("g3", &g3), def("g4", &g4) ]; DOSTRING(L, "x = get()\n"); TEST_CHECK(ptr_count == 1); DOSTRING(L, "f1(x)\n"); TEST_CHECK(ptr_count == 1); DOSTRING(L, "f2(x)\n"); TEST_CHECK(ptr_count == 1); DOSTRING(L, "f3(x)\n"); TEST_CHECK(ptr_count == 1); DOSTRING(L, "f4(x)\n"); TEST_CHECK(ptr_count == 1); DOSTRING(L, "g1(x)\n"); TEST_CHECK(ptr_count == 1); DOSTRING(L, "g2(x)\n"); TEST_CHECK(ptr_count == 1); DOSTRING(L, "g3(x)\n"); TEST_CHECK(ptr_count == 1); DOSTRING(L, "g4(x)\n"); TEST_CHECK(ptr_count == 1); DOSTRING(L, "x = nil\n" ); lua_gc(L, LUA_GCCOLLECT, 0); TEST_CHECK(ptr_count == 0); } luabind-1.1.1/test/test_properties.cpp000066400000000000000000000032171366245310300200540ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // This test expands on test_attributes.cpp, testing the new property // implementation features. #include "test.hpp" #include namespace { struct Base {}; } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("Base") .def(constructor<>()) ]; DOSTRING(L, "class 'Readonly' (Base)\n" " function Readonly:__init(x)\n" " Base.__init(self)\n" " self._x = x\n" " end\n" " function Readonly:getX()\n" " return self._x\n" " end\n" " Readonly.x = property(Readonly.getX)\n" ); DOSTRING(L, "class 'Readwrite' (Readonly)\n" " function Readwrite:__init(x)\n" " Readonly.__init(self, x)\n" " end\n" " function Readwrite:setX(x)\n" " self._x = x\n" " end\n" " Readwrite.x = property(Readonly.getX, Readwrite.setX)\n" ); DOSTRING(L, "r = Readonly(1)\n" "assert(r.x == 1)\n" ); DOSTRING_EXPECTED(L, "r = Readonly(1)\n" "r.x = 2\n" , "property 'x' is read only" ); DOSTRING(L, "r = Readwrite(2)\n" "assert(r.x == 2)\n" "r.x = 3\n" "assert(r.x == 3)\n" "assert(r._x == 3)\n" ); DOSTRING(L, "r = Readonly(1)\n" "r.y = 2\n" "assert(r.y == 2)\n" ); } luabind-1.1.1/test/test_scope.cpp000066400000000000000000000105611366245310300167710ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include #include // for yield namespace { int f() { return 1; } int f_(int) { return 2; } int f__(int) { return 3; } int g() { return 4; } int g_(int) { return 5; } int h() { return 6; } struct test_class : counted_type { test_class() : test(1) {} int test; }; struct test_class2 : counted_type { test_class2() {} int string_string(std::string const&, std::string const&) { return 1; } }; struct test_class_unnamed : counted_type { test_class_unnamed() {} int f() { return 42; } }; test_class_unnamed create_unnamed() { return test_class_unnamed(); } COUNTER_GUARD(test_class); COUNTER_GUARD(test_class2); COUNTER_GUARD(test_class_unnamed); } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("test_class2") .def(constructor<>()) .def("string_string", &test_class2::string_string) ]; module(L, "test") [ class_("test_class") .def(constructor<>()) .def_readonly("test", &test_class::test) .scope [ def("inner_fun", &f) ] .def("inner_fun2", &f) // this should become static .enum_("vals") [ value("val1", 1), value("val2", 2) ], def("f", &f), def("f", &f_), namespace_("inner") [ def("g", &g), def("f", &f__) ], namespace_("inner") [ def("g", &g_) ], class_() .def(constructor<>()) .def("f", &test_class_unnamed::f), def("create_unnamed", &create_unnamed) ]; module(L, "test") [ namespace_("inner") [ def("h", &h) ] ]; object test = newtable(L); module(test) [ namespace_("inner") [ def("h", &h) ] ]; DOSTRING(L, "assert(test.f() == 1)"); DOSTRING(L, "assert(test.f(3) == 2)"); DOSTRING(L, "assert(test.test_class.inner_fun() == 1)"); DOSTRING(L, "a = test.test_class()\n" "assert(a.test == 1)"); DOSTRING(L, "assert(a.inner_fun2() == 1)"); // free function DOSTRING(L, "b = test.test_class.val2\n" "assert(b == 2)"); DOSTRING(L, "assert(test.inner.g() == 4)"); DOSTRING(L, "assert(test.inner.g(7) == 5)"); DOSTRING(L, "assert(test.inner.f(4) == 3)"); DOSTRING(L, "assert(test.inner.h() == 6)"); globals(L)["test_object"] = test; DOSTRING(L, "assert(not inner)"); DOSTRING(L, "assert(test_object.inner.h() == 6)"); DOSTRING(L, "assert(not test_class_unnamed)"); DOSTRING(L, "u = test.create_unnamed()\n" "assert(u:f() == 42)"); DOSTRING_EXPECTED(L, "_ = test_class2.foo", "no static 'foo' in class 'test_class2'"); DOSTRING_EXPECTED(L, "_ = test.test_class['val1\\0foo']", "no static 'val1' (followed by embedded 0) in class 'test_class'"); DOSTRING_EXPECTED(L, "_ = test_class2[{}]", "no static value at table-index in class 'test_class2'"); } luabind-1.1.1/test/test_separation.cpp000066400000000000000000000033021366245310300200200ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include #include namespace { struct X {}; struct Y {}; luabind::scope test_separate_registration() { using namespace luabind; return class_("X") .def(constructor<>()), class_("Y") .def(constructor<>()) ; } } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ namespace_("Z") [ test_separate_registration() ] ]; DOSTRING(L, "x = Z.X()"); DOSTRING(L, "y = Z.Y()"); } luabind-1.1.1/test/test_set_instance_value.cpp000066400000000000000000000015011366245310300215250ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include void test_main(lua_State* L) { DOSTRING(L, "class 'X'\n" " function X:__init()\n" " self.value = 1\n" " self.second = 2\n" " end\n" "\n" "x = X()\n" "assert(x.value == 1)\n" "assert(x.second == 2)\n" "x.value = 2\n" "assert(x.value == 2)\n" "assert(x.second == 2)\n" "x.second = 3\n" "y = X()\n" "assert(y.value == 1)\n" "assert(y.second == 2)\n" "assert(x.value == 2)\n" "assert(x.second == 3)\n" ); } luabind-1.1.1/test/test_shadow.cpp000066400000000000000000000013171366245310300171440ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include using namespace luabind; struct X { void f() {} }; struct Y : X { void f() {} }; void test_main(lua_State* L) { module(L) [ class_("X") .def(constructor<>()) .def("f", &X::f), class_("Y") .def(constructor<>()) .def("f", &Y::f) ]; DOSTRING(L, "x = X()\n" "x:f()\n" ); DOSTRING(L, "x = Y()\n" "x:f()\n" ); } luabind-1.1.1/test/test_shared_ptr.cpp000066400000000000000000000066701366245310300200210ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include #include #include #include namespace { struct B: boost::enable_shared_from_this {}; struct I: B {}; struct D: I {}; struct X { X(int value_) : value(value_) {} int value; }; int get_value(boost::shared_ptr const& p) { return p->value; } boost::shared_ptr filter(boost::shared_ptr const& p, long expected_uc) { TEST_CHECK(p.use_count() == expected_uc); return p; } void needs_b(boost::shared_ptr const& p) { TEST_CHECK(p.use_count() == 2); } void needs_i(boost::shared_ptr const& p) { TEST_CHECK(p.use_count() == 2); } #ifndef LUABIND_NO_STD_SHARED_PTR struct B2: std::enable_shared_from_this {}; struct D2: B2 {}; void needs_b2(std::shared_ptr const& p) { TEST_CHECK(p.use_count() == 2); } #endif unsigned n_unref = 0; void on_state_unreferenced(lua_State* L) { TEST_CHECK(L); TEST_CHECK(luabind::is_state_unreferenced(L)); ++n_unref; } } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("X") .def(constructor()), def("get_value", &get_value), def("filter", &filter), class_ >("B") .def(constructor<>()), class_ >("I"), class_ >("D") .def(constructor<>()), def("needs_b", &needs_b), def("needs_i", &needs_i) #ifndef LUABIND_NO_STD_SHARED_PTR , class_ >("B2") .def(constructor<>()), class_ >("D2") .def(constructor<>()), def("needs_b2", &needs_b2) #endif ]; set_state_unreferenced_callback(L, &on_state_unreferenced); TEST_CHECK( get_state_unreferenced_callback(L) == &on_state_unreferenced); DOSTRING(L, "x = X(1)\n" "assert(get_value(x) == 1)\n" ); DOSTRING(L, "assert(x == filter(x, 1))\n" ); boost::shared_ptr spx(new X(2)); globals(L)["x2"] = spx; TEST_CHECK(spx.use_count() == 2); DOSTRING(L, "assert(get_value(x2) == 2)"); // Raw equality could only be provided here at the cost of creating a new // shared_ptr with a custom deleter, which in turn would mean that the // refered C++-object would be deleted when the lua_State is closed. DOSTRING(L, "filter(x2, 3)"); DOSTRING(L, "x = nil\n" "x2 = nil\n" "collectgarbage()\n" "collectgarbage()\n" ); TEST_CHECK(spx.use_count() == 1); DOSTRING(L, "d = D()\n" "needs_b(d)\n" // test that automatic upcasting works ); // upcast to class which is neither the template parameter of // enable_shared_from_this nor a direct match to the holder type: DOSTRING(L, "needs_i(d)"); #ifndef LUABIND_NO_STD_SHARED_PTR // And the same once again with std::shared_ptr: DOSTRING(L, "d2 = D2()\n" "needs_b2(d2)\n" // test that automatic upcasting works ); #endif TEST_CHECK(n_unref == 2); TEST_CHECK(is_state_unreferenced(L)); } luabind-1.1.1/test/test_simple_class.cpp000066400000000000000000000061371366245310300203420ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin // 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. #include "test.hpp" #include namespace { struct simple_class : counted_type { static int feedback; void f() { feedback = 1; } void f(int, int) {} void f(std::string a) { const char str[] = "foo\0bar"; if (a == std::string(str, sizeof(str)-1)) feedback = 2; } std::string g() { const char str[] = "foo\0bar"; return std::string(str, sizeof(str)-1); } }; int simple_class::feedback = 0; COUNTER_GUARD(simple_class); } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; typedef void(simple_class::*f_overload1)(); typedef void(simple_class::*f_overload2)(int, int); typedef void(simple_class::*f_overload3)(std::string); module(L) [ class_("simple") .def(constructor<>()) .def("f", static_cast(&simple_class::f)) .def("f", static_cast(&simple_class::f)) .def("f", static_cast(&simple_class::f)) .def("g", &simple_class::g) ]; DOSTRING(L, "class 'simple_derived' (simple)\n" " function simple_derived:__init() simple.__init(self) end\n" "a = simple_derived()\n" "a:f()\n"); TEST_CHECK(simple_class::feedback == 1); DOSTRING(L, "a:f('foo\\0bar')"); TEST_CHECK(simple_class::feedback == 2); DOSTRING(L, "b = simple_derived()\n" "a.foo = 'yo'\n" "assert(b.foo == nil)"); DOSTRING(L, "simple_derived.foobar = 'yi'\n" "assert(b.foobar == 'yi')\n" "assert(a.foobar == 'yi')\n"); simple_class::feedback = 0; DOSTRING_EXPECTED(L, "a:f('incorrect', 'parameters')", "No matching overload found, candidates:\n" "void f(simple&,std::string)\n" "void f(simple&,int,int)\n" "void f(simple&)"); DOSTRING(L, "if a:g() == \"foo\\0bar\" then a:f() end"); TEST_CHECK(simple_class::feedback == 1); } luabind-1.1.1/test/test_smart_ptr_attributes.cpp000066400000000000000000000026201366245310300221360ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include #include #include #include struct Foo { Foo() : m_baz(0) {} int m_baz; }; struct Bar { boost::shared_ptr getFoo() const { return m_foo; } void setFoo( boost::shared_ptr foo ) { m_foo = foo; } boost::shared_ptr m_foo; }; void test_main(lua_State* L) { using namespace luabind; bind_class_info(L); module( L ) [ class_ >( "Foo" ) .def( constructor<>() ) .def_readwrite("baz", &Foo::m_baz), class_ >( "Bar" ) .def( constructor<>() ) .property("fooz", &Bar::getFoo, &Bar::setFoo) .def_readwrite("foo", &Bar::m_foo) ]; dostring( L, "foo = Foo();"); dostring( L, "foo.baz = 42;"); dostring( L, "x = Bar();"); dostring( L, "x.fooz = foo;"); dostring( L, "print(type(x), class_info(x).name);"); dostring( L, "print(type(x.fooz), class_info(x.fooz).name);"); dostring( L, "print(type(x.foo), class_info(x.foo).name);"); // crashes here); } luabind-1.1.1/test/test_super_leak.cpp000066400000000000000000000020151366245310300200050ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include struct Foo { static std::size_t count; Foo() { ++count; } ~Foo() { --count; } }; std::size_t Foo::count = 0; void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("Foo") .def(constructor<>()) ]; // This used to leak the last created instance in one of the // upvalues to the "super" function. disable_super_deprecation(); DOSTRING(L, "class 'Bar' (Foo)\n" "function Bar.__init(self)\n" " Foo.__init(self)\n" "end\n" ); DOSTRING(L, "x = Bar()\n" ); assert(Foo::count == 1); DOSTRING(L, "x = nil\n" ); lua_gc(L, LUA_GCCOLLECT, 0); assert(Foo::count == 0); } luabind-1.1.1/test/test_table.cpp000066400000000000000000000016541366245310300167520ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include static void f(luabind::table<> const& x) { TEST_CHECK(luabind::type(x) == LUA_TTABLE); } static void g(luabind::table const& x) { TEST_CHECK(luabind::type(x) == LUA_TTABLE); } void test_main(lua_State* L) { using namespace luabind; module(L) [ def("f", &f), def("g", &g) ]; DOSTRING(L, "f {1,2,3}\n" "g {1,2,3}\n" ); DOSTRING_EXPECTED(L, "f(1)\n", "No matching overload found, candidates:\n" "void f(table const&)" ); DOSTRING_EXPECTED(L, "g(1)\n", "No matching overload found, candidates:\n" "void g(table const&)" ); } luabind-1.1.1/test/test_tag_function.cpp000066400000000000000000000020141366245310300203320ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include #include #include namespace { int f(int x, int y) { return x + y; } struct X { int f(int x, int y) { return x + y; } }; } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ def("f", tag_function(boost::bind(&f, 5, _1))), class_("X") .def(constructor<>()) .def("f", tag_function(boost::bind(&X::f, _1, 10, _2))) ]; DOSTRING(L, "assert(f(0) == 5)\n" "assert(f(1) == 6)\n" "assert(f(5) == 10)\n" ); DOSTRING(L, "x = X()\n" "assert(x:f(0) == 10)\n" "assert(x:f(1) == 11)\n" "assert(x:f(5) == 15)\n" ); } luabind-1.1.1/test/test_typetraits.cpp000066400000000000000000000047131366245310300200720ustar00rootroot00000000000000// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include #include #include using namespace luabind; using namespace luabind::detail; namespace { struct tester {}; } // namespace unnamed void test_main(lua_State*) { BOOST_STATIC_ASSERT(is_nonconst_reference::value); BOOST_STATIC_ASSERT(!is_nonconst_reference::value); BOOST_STATIC_ASSERT(is_nonconst_reference::value); BOOST_STATIC_ASSERT(!is_nonconst_reference::value); BOOST_STATIC_ASSERT(!is_const_reference::value); BOOST_STATIC_ASSERT(is_const_reference::value); BOOST_STATIC_ASSERT(!is_const_reference::value); BOOST_STATIC_ASSERT(is_const_reference::value); BOOST_STATIC_ASSERT(!is_const_pointer::value); BOOST_STATIC_ASSERT(is_const_pointer::value); BOOST_STATIC_ASSERT(!is_const_pointer::value); BOOST_STATIC_ASSERT(is_const_pointer::value); BOOST_STATIC_ASSERT(is_nonconst_pointer::value); BOOST_STATIC_ASSERT(!is_nonconst_pointer::value); BOOST_STATIC_ASSERT(is_nonconst_pointer::value); BOOST_STATIC_ASSERT(!is_nonconst_pointer::value); BOOST_STATIC_ASSERT(!is_const_reference::value); } luabind-1.1.1/test/test_unchecked.cpp000066400000000000000000000014661366245310300176150ustar00rootroot00000000000000// Copyright Christian Neumüller 2013. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include void test_main(lua_State* L) { DOSTRING(L, "class 'Foo'\n" "function Foo:__init() end\n" ); // Direct calls to metamethods used to cause access violations. DOSTRING_EXPECTED(L, "getmetatable(Foo).__index()", "[string \"getmetatable(Foo).__index()\"]:1: " "attempt to index a boolean value" ); DOSTRING(L, "foo = Foo()"); DOSTRING_EXPECTED(L, "getmetatable(foo).__index()", "[string \"getmetatable(foo).__index()\"]:1: " "attempt to index a boolean value" ); } luabind-1.1.1/test/test_unsigned_int.cpp000066400000000000000000000007541366245310300203510ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include void test_main(lua_State* L) { DOSTRING(L, "x = 4294967295"); unsigned int x = luabind::object_cast( luabind::globals(L)["x"]); unsigned int y = 4294967295UL; TEST_CHECK(x == y); } luabind-1.1.1/test/test_user_defined_converter.cpp000066400000000000000000000023431366245310300224020ustar00rootroot00000000000000// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include namespace { struct X { X(lua_Integer value_) : value(value_) {} lua_Integer value; }; lua_Integer take(X x) { return x.value; } X get(lua_Integer value) { return X(value); } } // namespace unnamed namespace luabind { template <> struct default_converter : native_converter_base { int compute_score(lua_State* L, int index) { return cv.compute_score(L, index); } X from(lua_State* L, int index) { return X(lua_tointeger(L, index)); } void to(lua_State* L, X const& x) { lua_pushinteger(L, x.value); } default_converter cv; }; } // namespace luabind void test_main(lua_State* L) { using namespace luabind; module(L) [ def("take", &take), def("get", &get) ]; DOSTRING(L, "assert(take(1) == 1)\n" "assert(take(2) == 2)\n" ); DOSTRING(L, "assert(get(1) == 1)\n" "assert(get(2) == 2)\n" ); } luabind-1.1.1/test/test_value_wrapper.cpp000066400000000000000000000046021366245310300205330ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin and Arvid Norberg // 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. #include #include #include struct X_tag; struct X { typedef X_tag value_wrapper_tag; }; namespace luabind { #ifdef LUABIND_USE_VALUE_WRAPPER_TAG template<> struct value_wrapper_traits { typedef boost::mpl::true_ is_specialized; }; #else // used on compilers supporting partial template specialization template<> struct value_wrapper_traits { typedef boost::mpl::true_ is_specialized; }; #endif } // namespace luabind BOOST_MPL_ASSERT(( luabind::is_value_wrapper )); BOOST_MPL_ASSERT_NOT(( luabind::is_value_wrapper )); BOOST_MPL_ASSERT_NOT(( luabind::is_value_wrapper )); BOOST_MPL_ASSERT(( luabind::is_value_wrapper_arg )); BOOST_MPL_ASSERT(( luabind::is_value_wrapper_arg )); BOOST_MPL_ASSERT(( luabind::is_value_wrapper_arg )); BOOST_MPL_ASSERT(( luabind::is_value_wrapper_arg )); BOOST_MPL_ASSERT_NOT(( luabind::is_value_wrapper_arg )); BOOST_MPL_ASSERT_NOT(( luabind::is_value_wrapper_arg )); BOOST_MPL_ASSERT(( luabind::is_value_wrapper_arg )); BOOST_MPL_ASSERT(( luabind::is_value_wrapper_arg )); BOOST_MPL_ASSERT(( luabind::is_value_wrapper_arg )); int main() { } luabind-1.1.1/test/test_vector_of_number.cpp000066400000000000000000000033251366245310300212160ustar00rootroot00000000000000// Copyright Christian Neumüller 2016. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // Test case by github.com/AndriyAstakhov #include "test.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace luabind; void test_main(lua_State* L) { BOOST_STATIC_ASSERT((boost::is_base_and_derived< number_converter, default_converter >::value)); BOOST_STATIC_ASSERT((boost::is_base_and_derived< number_converter, default_converter >::value)); BOOST_STATIC_ASSERT((!boost::is_base_and_derived< number_converter, default_converter >::value)); module(L) [ class_ >("vector_double") .def(constructor<>()) .def( "push_back", static_cast::*)(const double&)>( &std::vector::push_back)) ]; DOSTRING(L, "local vecDouble = vector_double()\n" "vecDouble:push_back(1.5)\n"); } luabind-1.1.1/test/test_vector_of_object.cpp000066400000000000000000000025261366245310300211760ustar00rootroot00000000000000// Copyright (c) 2005 Daniel Wallin // 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. #include "test.hpp" #include using namespace luabind; void test_main(lua_State* L) { std::vector v; v.push_back(object(L, 0)); for (std::vector::iterator i(v.begin()), e(v.end()); i != e; ++i) {} } luabind-1.1.1/test/test_virtual_inheritance.cpp000066400000000000000000000073461366245310300217260ustar00rootroot00000000000000// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include namespace { // Test the following hierarchy: // // X // / \. // Y Z // \ / // U struct X { X(int x_) : value(x_) {} virtual ~X() {} int f() const { return value; } int value; }; struct Y : virtual X { Y(int value_) : X(value_) , dummy(2) {} int g() const { return dummy; } int dummy; }; struct Z : virtual X { Z(int value_) : X(value_) , dummy(3) {} int h() const { return dummy; } int dummy; }; struct U : Y, Z { U(int value_) : X(value_) , Y(value_) , Z(value_) {} int dummy; }; X* upcast(U* p) { return p; } // This hiearchy tries to prove that conversion and caching works for all sub // object pointers: // // // Base Base // | | // Left Right // \ / // \ / // Derived // struct Base { Base(int value_) : value(value_) {} virtual ~Base() {} int value; }; struct Left : Base { Left() : Base(1) {} int left() const { return value; } int dummy; }; struct Right : Base { Right() : Base(2) {} int right() const { return value; } int dummy; }; struct Derived : Left, Right { int f() const { return 3; } int dummy; }; Base* left(Left* p) { return p; } Base* right(Right* p) { return p; } } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("X") .def("f", &X::f), class_("Y") .def("g", &Y::g), class_("Z") .def("h", &Z::h), class_ >("U") .def(constructor()), def("upcast", &upcast) ]; // Do everything twice to verify that caching works. DOSTRING(L, "x = U(1)\n" "assert(x:f() == 1)\n" "assert(x:f() == 1)\n" "assert(x:g() == 2)\n" "assert(x:g() == 2)\n" "assert(x:h() == 3)\n" "assert(x:h() == 3)\n" ); DOSTRING(L, "y = upcast(x)\n" "assert(y:f() == 1)\n" "assert(y:f() == 1)\n" "assert(y:g() == 2)\n" "assert(y:g() == 2)\n" "assert(y:h() == 3)\n" "assert(y:h() == 3)\n" ); module(L) [ class_("Base"), class_("Left") .def("left", &Left::left), class_("Right") .def("right", &Right::right), class_ >("Derived") .def(constructor<>()) .def("f", &Derived::f), def("left", &left), def("right", &right) ]; DOSTRING(L, "x = Derived()\n" "assert(x:left() == 1)\n" "assert(x:left() == 1)\n" "assert(x:right() == 2)\n" "assert(x:right() == 2)\n" "assert(x:f() == 3)\n" "assert(x:f() == 3)\n" ); DOSTRING(L, "y = left(x)\n" "assert(y:left() == 1)\n" "assert(y:left() == 1)\n" "assert(y:right() == 2)\n" "assert(y:right() == 2)\n" "assert(y:f() == 3)\n" "assert(y:f() == 3)\n" ); DOSTRING(L, "y = right(x)\n" "assert(y:left() == 1)\n" "assert(y:left() == 1)\n" "assert(y:right() == 2)\n" "assert(y:right() == 2)\n" "assert(y:f() == 3)\n" "assert(y:f() == 3)\n" ); } luabind-1.1.1/test/test_yield.cpp000066400000000000000000000052101366245310300167610ustar00rootroot00000000000000// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #include "test.hpp" #include #include // for if_<>::type namespace { struct test_class : counted_type { test_class() {} int f() const { return 5; } }; COUNTER_GUARD(test_class); } // namespace unnamed void test_main(lua_State* L) { using namespace luabind; module(L) [ class_("test") .def(constructor<>()) .def("f", &test_class::f, luabind::yield) ]; DOSTRING(L, "function h()\n" " coroutine.yield(4)" "end"); { lua_State* thread = lua_newthread(L); TEST_CHECK(resume_function(thread, "h") == 4); lua_pop(L, 1); // pop thread } DOSTRING(L, "function g(str)\n" " assert(str == 'foobar')\n" " a = test()" " for i = 1, 10 do\n" " assert(a:f() == i + 4)\n" " end\n" "end"); { lua_State* thread = lua_newthread(L); TEST_CHECK(resume_function(thread, "g", "foobar") == 5); for (int i = 1; i < 10; ++i) { TEST_CHECK(resume(thread, i + 4) == 5); } lua_pop(L, 1); // pop thread } { lua_State* thread = lua_newthread(L); object g = globals(thread)["g"]; TEST_CHECK(resume_function(g, "foobar") == 5); for (int i = 1; i < 10; ++i) { TEST_CHECK(resume(thread, i + 4) == 5); } lua_pop(L, 1); // pop thread } }