├── .gitignore ├── .gitmodules ├── .travis.yml ├── CMakeLists.txt ├── Doxyfile ├── LICENSE ├── README.md ├── include ├── LuaException.h ├── LuaFunctor.h ├── LuaPrimitives.h ├── LuaRef.h ├── LuaReturn.h ├── LuaStack.h ├── LuaStackItem.h ├── LuaState.h ├── LuaValue.h └── Traits.h └── test ├── get_test.cpp ├── lambda_test.cpp ├── main.cpp ├── ref_test.cpp ├── set_test.cpp ├── state_test.cpp ├── test.h ├── types_test.cpp └── values_test.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | CMakeCache.txt 2 | CMakeFiles 3 | Makefile 4 | cmake_install.cmake 5 | install_manifest.txt 6 | 7 | docs/* 8 | build/* -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "tools"] 2 | path = tools 3 | url = https://github.com/LuaDist/Tools 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: cpp 2 | 3 | compiler: 4 | - clang 5 | - gcc 6 | 7 | env: 8 | matrix: 9 | - LUA=lua5.1 LIBLUA=liblua5.1-dev LUA_INCDIR=/usr/include/lua5.1 LUA_LIB=lua5.1 10 | - LUA=lua5.2 LIBLUA=liblua5.2-dev LUA_INCDIR=/usr/include/lua5.2 LUA_LIB=lua5.2 11 | - LUA=luajit LIBLUA=libluajit-5.1-dev LUA_INCDIR=/usr/include/luajit-2.0 LUA_LIB=luajit-5.1 12 | 13 | before_install: 14 | 15 | # Clone submodules 16 | - git submodule update --init --recursive 17 | 18 | install: 19 | # Install Lua library 20 | - sudo apt-get install $LUA -y 21 | - sudo apt-get install $LIBLUA -y 22 | 23 | before_script: 24 | - mkdir build 25 | - cd build 26 | - cmake .. -DLUA_LIBRARIES=$LUA_LIB -DLUA_INCLUDE_DIR=$LUA_INCDIR 27 | 28 | script: 29 | - make 30 | - ./state_test 31 | - ./types_test 32 | - ./get_test 33 | - ./set_test 34 | - ./values_test 35 | - ./ref_test 36 | - ./lambda_test 37 | 38 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8) 2 | 3 | set (PROJECT_NAME "LuaState") 4 | project(${PROJECT_NAME}) 5 | 6 | ################################################################################################ 7 | ################################################################################################ 8 | 9 | # Must be executed BEFORE add_executable! 10 | macro(group_folder FOLDER) 11 | file(GLOB SOURCE_GROUP ${FOLDER}/*.c ${FOLDER}/*.h ${FOLDER}/*.cpp ${FOLDER}/*.hpp) 12 | string(REGEX REPLACE "/" "\\\\\\\\" SOURCE_GROUP_NAME ${FOLDER}) 13 | source_group(${SOURCE_GROUP_NAME} FILES ${SOURCE_GROUP}) 14 | endmacro() 15 | 16 | macro(add_test FILE_NAME) 17 | add_executable(${FILE_NAME} test/${FILE_NAME}.cpp test/test.h) 18 | target_link_libraries(${FILE_NAME} ${LUA_LIBRARIES}) 19 | add_dependencies(ALL_TEST ${FILE_NAME}) 20 | endmacro() 21 | 22 | ################################################################################################ 23 | ################################################################################################ 24 | 25 | include(CheckCXXCompilerFlag) 26 | CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11) 27 | CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X) 28 | if(COMPILER_SUPPORTS_CXX11) 29 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") 30 | elseif(COMPILER_SUPPORTS_CXX0X) 31 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") 32 | else() 33 | message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.") 34 | endif() 35 | 36 | ################################################################################################ 37 | ################################################################################################ 38 | 39 | set (CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/Tools/CMake") 40 | 41 | 42 | group_folder("include") 43 | set(INCLUDE_FILES ${SOURCE_GROUP}) 44 | include_directories(include) 45 | 46 | if(LUA_INCLUDE_DIR) 47 | include_directories(${LUA_INCLUDE_DIR}) 48 | else(LUA_INCLUDE_DIR) 49 | find_package(Lua) 50 | include_directories(${LUA_INCLUDE_DIR}) 51 | endif(LUA_INCLUDE_DIR) 52 | 53 | ################################################################################################ 54 | ################################################################################################ 55 | 56 | add_executable(ALL_TEST test/main.cpp ${INCLUDE_FILES}) 57 | 58 | add_test("state_test") 59 | add_test("types_test") 60 | add_test("get_test") 61 | add_test("set_test") 62 | add_test("ref_test") 63 | add_test("lambda_test") 64 | add_test("values_test") 65 | 66 | ################################################################################################ 67 | ################################################################################################ 68 | 69 | # Flags for MacOS which links directly or indirectly against LuaJIT 70 | if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") 71 | set( CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pagezero_size 10000 -image_base 100000000") 72 | endif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") 73 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {2014} {Simon Mikuda} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/AdUki/LuaState.png)](https://travis-ci.org/AdUki/LuaState) 2 | 3 | LuaState 4 | ======== 5 | 6 | Lightweight Lua51 binding library for C++11. 7 | 8 | If you find bugs, feel free to create new issues. Also I will gladly to hear new suggestions and improvements :) 9 | 10 | #### Main features: 11 | * While getting values from `lua_State*` library does not use vectors or lists for memoization of key values. It uses values which are already in native Lua C API stack and simple int variables to index them. 12 | * To keep Lua C API stack clean. When we create lua_State*, library automaticaly creates priority queue, where we keep when and which Lua values can be removed from stack. This can be big performacne gain while querying deep structures from tables. 13 | * We can bind lamba functions, where captured variables are managed by Lua garbage collector. 14 | * No nesting C preprocessor macros to bind our classes. We can use only C++11 code and bind our classes with capture lists of lambdas. This way we can bind anything: function, variables, pointers... 15 | * When we can bind almost ANY function. There is no predefined form. In that way we can avoid boilerplate code and parameters can be self documented with their names. 16 | * Multiple return values with `std::tuples` - `lua::tie` (same syntax as `std::tie`). 17 | * We can directly pass lua values (tables for instance) around in C++ code. For example we can return table from one Lua function and put this table as parameter to another Lua function. All this just in C++. 18 | 19 | ### Setting it up 20 | 21 | Just create lua::State variable, which will initialize lus_State and loads up standard libraries. It will close state automatically in destructor. 22 | 23 | ~~~~~~~~~~~~~~~{.cpp} 24 | #include 25 | int main() { 26 | lua::State state; 27 | state.doString("print 'Hello world!'"); 28 | } 29 | ~~~~~~~~~~~~~~~ 30 | 31 | ### Reading values 32 | 33 | Reading values from Lua state is very simple. It is using templates, so type information is required. 34 | 35 | ~~~~~~~~~~~~~~~{.cpp} 36 | state.doString("number = 100; text = 'hello'"); 37 | int number =state["number"]; 38 | std::string text = state["text"]; 39 | ~~~~~~~~~~~~~~~ 40 | 41 | When reading values from tables, you just chain [] operators. 42 | 43 | ~~~~~~~~~~~~~~~{.cpp} 44 | state.doString("table = { a = 1, b = { 2 }, c = 3}"); 45 | int a = state["table"]["a"]; 46 | int b = state["table"]["b"][1]; 47 | int c = state["table"]["c"]; 48 | ~~~~~~~~~~~~~~~ 49 | 50 | ### Calling functions 51 | 52 | You can call lua functions with () operator with various number of arguments while returning none, one or more values. 53 | 54 | ~~~~~~~~~~~~~~~{.cpp} 55 | state.doString("function setFoo() foo = "hello" end"); 56 | state.doString("function getFoo() return foo end"); 57 | 58 | state["setFoo"]() 59 | std::string text = state["getFoo"]() 60 | 61 | state.doString("function add(x, y) return x + y end"); 62 | int result = state["add"](1,2); 63 | 64 | state.doString("function iWantMore() return 20, 13.8, 'MORE' end"); 65 | float number; 66 | std::string text; 67 | lua::tie(result, number, text) = state["iWantMore"](); 68 | ~~~~~~~~~~~~~~~ 69 | 70 | ### Setting values 71 | 72 | Is also pretty straightforward... 73 | 74 | ~~~~~~~~~~~~~~~{.cpp} 75 | state.doString("table = { a = 1, b = { 2 }, c = 3}"); 76 | state["table"].set("a", 100); 77 | state["table"]["b"].set(1, 200); 78 | state["table"].set("c", 300); 79 | 80 | state.set("newTable", lua::Table()); 81 | state["newTable"].set(1, "a"); 82 | state["newTable"].set(2, "b"); 83 | state["newTable"].set(3, "c"); 84 | ~~~~~~~~~~~~~~~ 85 | 86 | ### Setting functions 87 | 88 | You can bind C functions, lambdas and std::functions with bind. These instances are managed by Lua garbage collector and will be destroyed when you will lost last reference in Lua state to them. 89 | 90 | ~~~~~~~~~~~~~~~{.cpp} 91 | void sayHello() { printf("Hello!\n"); } 92 | state.set("cfunction", &sayHello); 93 | state["cfunction"](); // Hello! 94 | 95 | int value = 20; 96 | state.set("lambda", [value](int a, int b) -> int { return (a*b)/value; } ) 97 | int result = state["lambda"](12, 5); // result = 3 98 | ~~~~~~~~~~~~~~~ 99 | 100 | They can return one or more values with use of std::tuple. For example, when you want to register more functions, you can return bundled in tuple... 101 | 102 | ~~~~~~~~~~~~~~~{.cpp} 103 | state.set("getFncs", []() 104 | -> std::tuple, std::function, std::function> { 105 | return { 106 | []() -> int { return 100; }, 107 | []() -> int { return 200; }, 108 | []() -> int { return 300; } 109 | }; 110 | } ); 111 | state.doString("fnc1, fnc2, fnc3 = getFncs()" 112 | "print(fnc1(), fnc2(), fnc3())"); // 100 200 300 113 | ~~~~~~~~~~~~~~~ 114 | 115 | You can easily register your classes functions with `this` pointer passing to lambda capture or bind... 116 | 117 | ~~~~~~~~~~~~~~~{.cpp} 118 | struct Foo { 119 | int a; int b; 120 | 121 | void setB(int value) { b = value; } 122 | Foo(lua::State& state) { 123 | state.set("Foo_setA", [this](int value) { a = value; } ); 124 | state.set("Foo_setB", std::function(std::bind(&Foo::setB, this, _1)) ); 125 | } 126 | }; 127 | ~~~~~~~~~~~~~~~ 128 | 129 | ### Managing C++ classes by garbage collector 130 | 131 | It is highly recommended to use shared pointers and then you will have garbage collected classes in C++. Objects will exist util there is last instance of shared pointer and they will be immediately released when all shared pointer instances are gone. 132 | 133 | Our resource: 134 | 135 | ~~~~~~~~~~~~~~~{.cpp} 136 | struct Resource { 137 | Resource() { printf("New resource\n"); } 138 | ~Resource() { printf("Released resource\n"); } 139 | 140 | void doStuff() { printf("Working..."); } 141 | }; 142 | ~~~~~~~~~~~~~~~ 143 | 144 | Resource using and released by garbage collector: 145 | 146 | ~~~~~~~~~~~~~~~{.cpp} 147 | std::shared_ptr resource = std::make_shared(); // New resource 148 | state.set("useResource", [resource]() { resource->doStuff(); } ); 149 | resource.reset(); 150 | 151 | state.doString("useResource()"); // Working 152 | state.doString("useResource = nil; collectgarbage()"); // Released resource 153 | ~~~~~~~~~~~~~~~ 154 | -------------------------------------------------------------------------------- /include/LuaException.h: -------------------------------------------------------------------------------- 1 | // 2 | // LuaException.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 17/03/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #pragma once 10 | 11 | #include 12 | 13 | namespace lua { 14 | 15 | namespace stack { 16 | 17 | inline void dump (lua_State *L) { 18 | int i; 19 | int top = lua_gettop(L); 20 | for (i = 1; i <= top; i++) { /* repeat for each level */ 21 | int t = lua_type(L, i); 22 | switch (t) { 23 | case LUA_TSTRING: /* strings */ 24 | printf("`%s'", lua_tostring(L, i)); 25 | break; 26 | 27 | case LUA_TBOOLEAN: /* booleans */ 28 | printf(lua_toboolean(L, i) ? "true" : "false"); 29 | break; 30 | 31 | case LUA_TNUMBER: /* numbers */ 32 | printf("%g", lua_tonumber(L, i)); 33 | break; 34 | 35 | default: /* other values */ 36 | printf("%s", lua_typename(L, t)); 37 | break; 38 | 39 | } 40 | printf(" "); /* put a separator */ 41 | } 42 | printf("\n"); /* end the listing */ 43 | } 44 | 45 | } 46 | 47 | ////////////////////////////////////////////////////////////////////////////////////////////// 48 | class LoadError: public std::exception 49 | { 50 | std::string _message; 51 | 52 | public: 53 | LoadError(lua_State* luaState) 54 | : _message(lua_tostring(luaState, -1)) { lua_pop(luaState, 1); } 55 | 56 | virtual ~LoadError() throw() {} 57 | virtual const char* what() const throw() { return _message.c_str(); } 58 | }; 59 | 60 | ////////////////////////////////////////////////////////////////////////////////////////////// 61 | class RuntimeError: public std::exception 62 | { 63 | std::string _message; 64 | 65 | public: 66 | RuntimeError(lua_State* luaState) 67 | : _message(lua_tostring(luaState, -1)) { lua_pop(luaState, 1); } 68 | 69 | virtual ~RuntimeError() throw() {} 70 | virtual const char* what() const throw() { return _message.c_str(); } 71 | }; 72 | 73 | ////////////////////////////////////////////////////////////////////////////////////////////// 74 | class TypeMismatchError : public std::exception 75 | { 76 | int _stackIndex; 77 | char _message[255]; 78 | 79 | public: 80 | TypeMismatchError(lua_State* luaState, int index) 81 | : _stackIndex(index) { } 82 | 83 | virtual ~TypeMismatchError() throw() { } 84 | virtual const char* what() const throw() { 85 | sprintf((char *)_message, "Type mismatch error at index %d.", _stackIndex); 86 | return _message; 87 | } 88 | }; 89 | } -------------------------------------------------------------------------------- /include/LuaFunctor.h: -------------------------------------------------------------------------------- 1 | // 2 | // LuaFunctor.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 22/03/14. 6 | // 7 | // See LICENSE and README.md files 8 | // 9 | 10 | #pragma once 11 | 12 | namespace lua { 13 | 14 | ////////////////////////////////////////////////////////////////////////////////////////////// 15 | /// Base functor class with call function. It is used for registering lamdas, or regular functions 16 | struct BaseFunctor 17 | { 18 | BaseFunctor() { 19 | LUASTATE_DEBUG_LOG("Functor %p created!", this); 20 | } 21 | 22 | virtual ~BaseFunctor() { 23 | LUASTATE_DEBUG_LOG("Functor %p destructed!", this); 24 | } 25 | 26 | /// In Lua numbers of argumens can be different so here we will handle these situations. 27 | /// 28 | /// @param luaState Pointer of Lua state 29 | inline void prepareFunctionCall(lua_State* luaState, int requiredValues) { 30 | 31 | // First item is our pushed userdata 32 | if (stack::top(luaState) > requiredValues + 1) { 33 | stack::settop(luaState, requiredValues + 1); 34 | } 35 | } 36 | 37 | /// Virtual function that will make Lua call to our functor. 38 | /// 39 | /// @param luaState Pointer of Lua state 40 | virtual int call(lua_State* luaState) = 0; 41 | }; 42 | 43 | ////////////////////////////////////////////////////////////////////////////////////////////// 44 | /// Functor with return values 45 | template 46 | struct Functor : public BaseFunctor { 47 | std::function function; 48 | 49 | /// Constructor creates functor to be pushed to Lua interpret 50 | Functor(std::function function) : BaseFunctor(), function(function) {} 51 | 52 | /// We will make Lua call to our functor. 53 | /// 54 | /// @note When we call function from Lua to C, they have their own stack, where in the first position is our binded userdata and next position are pushed arguments 55 | /// 56 | /// @param luaState Pointer of Lua state 57 | int call(lua_State* luaState) { 58 | Ret value = traits::apply(function, stack::get_and_pop(luaState, nullptr, 2)); 59 | return stack::push(luaState, value); 60 | } 61 | }; 62 | 63 | ////////////////////////////////////////////////////////////////////////////////////////////// 64 | /// Functor with no return values 65 | template 66 | struct Functor : public BaseFunctor { 67 | std::function function; 68 | 69 | /// Constructor creates functor to be pushed to Lua interpret 70 | Functor(std::function function) : BaseFunctor(), function(function) {} 71 | 72 | /// We will make Lua call to our functor. 73 | /// 74 | /// @note When we call function from Lua to C, they have their own stack, where in the first position is our binded userdata and next position are pushed arguments 75 | /// 76 | /// @param luaState Pointer of Lua state 77 | int call(lua_State* luaState) { 78 | traits::apply_no_ret(function, stack::get_and_pop(luaState, nullptr, 2)); 79 | return 0; 80 | } 81 | }; 82 | 83 | namespace stack { 84 | 85 | template 86 | inline int push(lua_State* luaState, Ret(*function)(Args...)) { 87 | BaseFunctor** udata = (BaseFunctor **)lua_newuserdata(luaState, sizeof(BaseFunctor *)); 88 | *udata = new Functor(function); 89 | 90 | luaL_getmetatable(luaState, "luaL_Functor"); 91 | lua_setmetatable(luaState, -2); 92 | return 1; 93 | } 94 | 95 | template 96 | inline int push(lua_State* luaState, std::function function) { 97 | BaseFunctor** udata = (BaseFunctor **)lua_newuserdata(luaState, sizeof(BaseFunctor *)); 98 | *udata = new Functor(function); 99 | 100 | luaL_getmetatable(luaState, "luaL_Functor"); 101 | lua_setmetatable(luaState, -2); 102 | return 1; 103 | } 104 | 105 | template 106 | inline int push(lua_State* luaState, T function) 107 | { 108 | push(luaState, (typename traits::function_traits::Function)(function)); 109 | return 1; 110 | } 111 | 112 | } 113 | } -------------------------------------------------------------------------------- /include/LuaPrimitives.h: -------------------------------------------------------------------------------- 1 | // 2 | // LuaPrimitives.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 18/03/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #pragma once 10 | 11 | namespace lua 12 | { 13 | /// Lua table type 14 | struct Table {}; 15 | 16 | /// Any Lua function, C function, or table/userdata with __call metamethod 17 | struct Callable {}; 18 | 19 | typedef lua_Number Number; 20 | 21 | typedef int Integer; 22 | 23 | typedef bool Boolean; 24 | 25 | typedef const char* String; 26 | 27 | typedef std::nullptr_t Nil; 28 | 29 | typedef void* Pointer; 30 | } 31 | -------------------------------------------------------------------------------- /include/LuaRef.h: -------------------------------------------------------------------------------- 1 | // 2 | // LuaRef.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 17/04/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #pragma once 10 | 11 | namespace lua { 12 | 13 | /// Reference to Lua value. Can be created from any lua::Value 14 | class Ref 15 | { 16 | /// Pointer of Lua state 17 | lua_State* _luaState; 18 | detail::DeallocQueue* _deallocQueue; 19 | 20 | /// Key of referenced value in LUA_REGISTRYINDEX 21 | int _refKey; 22 | 23 | void createRefKey() { 24 | _refKey = luaL_ref(_luaState, LUA_REGISTRYINDEX); 25 | } 26 | 27 | public: 28 | 29 | Ref() : _luaState(nullptr) {} 30 | 31 | // Copy and move constructors just use operator functions 32 | Ref(const Value& value) { operator=(value); } 33 | Ref(Value&& value) { operator=(value); } 34 | 35 | ~Ref() { 36 | luaL_unref(_luaState, LUA_REGISTRYINDEX, _refKey); 37 | } 38 | 39 | /// Copy assignment. Creates lua::Ref from lua::Value. 40 | void operator= (const Value& value) { 41 | _luaState = value._stack->state; 42 | _deallocQueue = value._stack->deallocQueue; 43 | 44 | // Duplicate top value 45 | lua_pushvalue(_luaState, -1); 46 | 47 | // Create reference to registry 48 | createRefKey(); 49 | } 50 | 51 | /// Move assignment. Creates lua::Ref from lua::Value from top of stack and pops it 52 | void operator= (Value&& value) { 53 | _luaState = value._stack->state; 54 | _deallocQueue = value._stack->deallocQueue; 55 | 56 | if (value._stack->pushed > 0) 57 | value._stack->pushed -= 1; 58 | else 59 | value._stack->top -= 1; 60 | 61 | // Create reference to registry 62 | createRefKey(); 63 | } 64 | 65 | /// Creates lua::Value from lua::Ref 66 | /// 67 | /// @return lua::Value with referenced value on stack 68 | Value unref() const { 69 | lua_rawgeti(_luaState, LUA_REGISTRYINDEX, _refKey); 70 | return Value(std::make_shared(_luaState, _deallocQueue, stack::top(_luaState) - 1, 1, 0)); 71 | } 72 | 73 | bool isInitialized() const { return _luaState != nullptr; } 74 | }; 75 | 76 | 77 | } -------------------------------------------------------------------------------- /include/LuaReturn.h: -------------------------------------------------------------------------------- 1 | // 2 | // LuaReturn.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 18/03/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #pragma once 10 | 11 | namespace lua { 12 | 13 | ////////////////////////////////////////////////////////////////////////////////////////////// 14 | namespace stack { 15 | 16 | 17 | ////////////////////////////////////////////////////////////////////////////////////////////// 18 | template 19 | class Pop { 20 | 21 | friend class lua::Value; 22 | 23 | /// Function get single value from lua stack 24 | template 25 | static inline T readValue(lua_State* luaState, 26 | detail::DeallocQueue* deallocQueue, 27 | int stackTop) 28 | { 29 | // if (!stack::check(luaState, stackTop)) 30 | // throw lua::TypeMismatchError(luaState, stackTop); 31 | 32 | return lua::Value(std::make_shared(luaState, deallocQueue, stackTop - 1, 1, 0)); 33 | } 34 | 35 | /// Function creates indexes for mutli values and get them from stack 36 | template 37 | static inline std::tuple unpackMultiValues(lua_State* luaState, 38 | detail::DeallocQueue* deallocQueue, 39 | int stackTop, 40 | traits::indexes) 41 | { 42 | return std::make_tuple(readValue(luaState, deallocQueue, Is + stackTop)...); 43 | } 44 | 45 | public: 46 | 47 | /// Function get multiple return values from lua stack 48 | static inline std::tuple getMultiValues(lua_State* luaState, 49 | detail::DeallocQueue* deallocQueue, 50 | int stackTop) 51 | { 52 | return unpackMultiValues(luaState, deallocQueue, stackTop, typename traits::indexes_builder::index()); 53 | } 54 | }; 55 | 56 | /// Function expects that number of elements in tuple and number of pushed values in stack are same. Applications takes care of this requirement by popping overlapping values before calling this function 57 | template 58 | inline std::tuple get_and_pop(lua_State* luaState, 59 | detail::DeallocQueue* deallocQueue, 60 | int stackTop) 61 | { 62 | return Pop::getMultiValues(luaState, deallocQueue, stackTop); 63 | } 64 | 65 | 66 | } 67 | 68 | ////////////////////////////////////////////////////////////////////////////////////////////// 69 | /// Class for automaticly cas lua::Function instance to multiple return values with lua::tie 70 | template 71 | class Return 72 | { 73 | /// Return values 74 | std::tuple _tuple; 75 | 76 | public: 77 | 78 | /// Constructs class with given arguments 79 | /// 80 | /// @param args Return values 81 | Return(Ts&&... args) 82 | : _tuple(args...) {} 83 | 84 | /// Operator sets values to std::tuple 85 | /// 86 | /// @param function Function being called 87 | void operator= (const Value& value) { 88 | 89 | int requiredValues = sizeof...(Ts) < value._stack->pushed ? sizeof...(Ts) : value._stack->pushed; 90 | 91 | // When there are more returned values than variables in tuple, we will clear values that are not needed 92 | if (requiredValues < (value._stack->grouped + 1)) { 93 | 94 | int currentStackTop = stack::top(value._stack->state); 95 | 96 | // We will check if we haven't pushed some other new lua::Value to stack 97 | if (value._stack->top + value._stack->pushed == currentStackTop) 98 | stack::settop(value._stack->state, value._stack->top + requiredValues); 99 | else 100 | value._stack->deallocQueue->push(detail::DeallocStackItem(value._stack->top, value._stack->pushed)); 101 | } 102 | 103 | // We will take pushed values and distribute them to returned lua::Values 104 | value._stack->pushed = 0; 105 | 106 | _tuple = stack::get_and_pop::type...>(value._stack->state, value._stack->deallocQueue, value._stack->top + 1); 107 | } 108 | 109 | }; 110 | 111 | /// Use this function when you want to retrieve multiple return values from lua::Function 112 | template 113 | Return tie(Ts&&... args) { 114 | return Return(args...); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /include/LuaStack.h: -------------------------------------------------------------------------------- 1 | // 2 | // LuaStack.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 18/03/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #pragma once 10 | 11 | #include 12 | 13 | namespace lua { namespace stack { 14 | 15 | ////////////////////////////////////////////////////////////////////////////////////////////// 16 | 17 | inline int top(lua_State* luaState) { 18 | return lua_gettop(luaState); 19 | } 20 | 21 | ////////////////////////////////////////////////////////////////////////////////////////////// 22 | 23 | template 24 | inline int push(lua_State* luaState, T value); 25 | 26 | template 27 | inline int push(lua_State* luaState, T value, Ts... values) { 28 | push(luaState, std::forward(value)); 29 | push(luaState, values...); 30 | return sizeof...(Ts) + 1; 31 | } 32 | 33 | template 34 | void push_tuple(lua_State* luaState, traits::index_tuple< Indexes... >, const std::tuple& tup) 35 | { 36 | push(luaState, std::get(tup)...); 37 | } 38 | 39 | template 40 | inline int push(lua_State* luaState, const std::tuple& tuple) 41 | { 42 | push_tuple(luaState, typename traits::make_indexes::type(), tuple); 43 | return sizeof...(Args); 44 | } 45 | 46 | inline int push(lua_State* luaState) { return 0; } 47 | 48 | template<> 49 | inline int push(lua_State* luaState, int value) { 50 | LUASTATE_DEBUG_LOG(" PUSH %d", value); 51 | lua_pushnumber(luaState, value); 52 | return 1; 53 | } 54 | 55 | template<> 56 | inline int push(lua_State* luaState, short int value) { 57 | LUASTATE_DEBUG_LOG(" PUSH %d", value); 58 | lua_pushnumber(luaState, value); 59 | return 1; 60 | } 61 | 62 | template<> 63 | inline int push(lua_State* luaState, long long int value) { 64 | LUASTATE_DEBUG_LOG(" PUSH %lld", value); 65 | lua_pushnumber(luaState, value); 66 | return 1; 67 | } 68 | 69 | template<> 70 | inline int push(lua_State* luaState, unsigned short int value) { 71 | LUASTATE_DEBUG_LOG(" PUSH %d", value); 72 | lua_pushnumber(luaState, value); 73 | return 1; 74 | } 75 | 76 | template<> 77 | inline int push(lua_State* luaState, unsigned int value) { 78 | LUASTATE_DEBUG_LOG(" PUSH %ud", value); 79 | lua_pushnumber(luaState, value); 80 | return 1; 81 | } 82 | 83 | template<> 84 | inline int push(lua_State* luaState, long int value) { 85 | LUASTATE_DEBUG_LOG(" PUSH %ld", value); 86 | lua_pushnumber(luaState, value); 87 | return 1; 88 | } 89 | 90 | template<> 91 | inline int push(lua_State* luaState, unsigned long int value) { 92 | LUASTATE_DEBUG_LOG(" PUSH %lud", value); 93 | lua_pushnumber(luaState, value); 94 | return 1; 95 | } 96 | 97 | template<> 98 | inline int push(lua_State* luaState, unsigned long long int value) { 99 | LUASTATE_DEBUG_LOG(" PUSH %llud", value); 100 | lua_pushnumber(luaState, value); 101 | return 1; 102 | } 103 | 104 | template<> 105 | inline int push(lua_State* luaState, char value) { 106 | LUASTATE_DEBUG_LOG(" PUSH %c\n", value); 107 | char string[2]; 108 | string[0] = value; 109 | string[1] = '\0'; 110 | lua_pushstring(luaState, string); 111 | return 1; 112 | } 113 | 114 | template<> 115 | inline int push(lua_State* luaState, unsigned char value) { 116 | LUASTATE_DEBUG_LOG(" PUSH %c\n", value); 117 | char string[2]; 118 | string[0] = static_cast(value); 119 | string[1] = '\0'; 120 | lua_pushstring(luaState, string); 121 | return 1; 122 | } 123 | 124 | template<> 125 | inline int push(lua_State* luaState, const char* value) { 126 | LUASTATE_DEBUG_LOG(" PUSH %s", value); 127 | lua_pushstring(luaState, value); 128 | return 1; 129 | } 130 | 131 | template<> 132 | inline int push(lua_State* luaState, std::string value) { 133 | LUASTATE_DEBUG_LOG(" PUSH %s", value.c_str()); 134 | lua_pushstring(luaState, value.c_str()); 135 | return 1; 136 | } 137 | 138 | template<> 139 | inline int push(lua_State* luaState, const unsigned char* value) { 140 | LUASTATE_DEBUG_LOG(" PUSH %s", value); 141 | lua_pushstring(luaState, reinterpret_cast(value)); 142 | return 1; 143 | } 144 | 145 | template<> 146 | inline int push(lua_State* luaState, float value) { 147 | LUASTATE_DEBUG_LOG(" PUSH %lf\n", value); 148 | lua_pushnumber(luaState, value); 149 | return 1; 150 | } 151 | 152 | template<> 153 | inline int push(lua_State* luaState, double value) { 154 | LUASTATE_DEBUG_LOG(" PUSH %lf\n", value); 155 | lua_pushnumber(luaState, value); 156 | return 1; 157 | } 158 | 159 | template<> 160 | inline int push(lua_State* luaState, long double value) { 161 | LUASTATE_DEBUG_LOG(" PUSH %Lf\n", value); 162 | lua_pushnumber(luaState, value); 163 | return 1; 164 | } 165 | 166 | template<> 167 | inline int push(lua_State* luaState, lua::Boolean value) { 168 | LUASTATE_DEBUG_LOG(" PUSH %s", value ? "true" : "false"); 169 | lua_pushboolean(luaState, value); 170 | return 1; 171 | } 172 | 173 | template<> 174 | inline int push(lua_State* luaState, lua::Nil value) { 175 | LUASTATE_DEBUG_LOG(" PUSH null\n"); 176 | lua_pushnil(luaState); 177 | return 1; 178 | } 179 | 180 | template<> 181 | inline int push(lua_State* luaState, lua::Pointer value) { 182 | LUASTATE_DEBUG_LOG(" PUSH %p\n", value); 183 | lua_pushlightuserdata(luaState, value); 184 | return 1; 185 | } 186 | 187 | template<> 188 | inline int push(lua_State* luaState, Table value) { 189 | LUASTATE_DEBUG_LOG(" PUSH newTable\n"); 190 | lua_newtable(luaState); 191 | return 1; 192 | } 193 | 194 | inline int push_str(lua_State* luaState, const char* value, int lenght) { 195 | LUASTATE_DEBUG_LOG(" PUSH %s", value); 196 | lua_pushlstring(luaState, value, lenght); 197 | return 1; 198 | } 199 | 200 | ////////////////////////////////////////////////////////////////////////////////////////////// 201 | 202 | template 203 | inline bool check(lua_State* luaState, int index); 204 | 205 | template<> 206 | inline bool check(lua_State* luaState, int index) 207 | { 208 | if (!lua_isnumber(luaState, index)) 209 | return false; 210 | 211 | lua_Number eps = std::numeric_limits::epsilon(); 212 | double number = lua_tonumber(luaState, index); 213 | return fabs(number - static_cast(number + eps)) <= eps; 214 | } 215 | 216 | template<> 217 | inline bool check(lua_State* luaState, int index) 218 | { 219 | return lua_isnumber(luaState, index); 220 | } 221 | 222 | template<> 223 | inline bool check(lua_State* luaState, int index) 224 | { 225 | return lua_isboolean(luaState, index); 226 | } 227 | 228 | template<> 229 | inline bool check(lua_State* luaState, int index) 230 | { 231 | // Lua is treating numbers also like strings, because they are always convertible to string 232 | if (lua_isnumber(luaState, index)) 233 | return false; 234 | 235 | return lua_isstring(luaState, index); 236 | } 237 | 238 | template<> 239 | inline bool check(lua_State* luaState, int index) 240 | { 241 | return lua_isnoneornil(luaState, index); 242 | } 243 | 244 | template<> 245 | inline bool check(lua_State* luaState, int index) 246 | { 247 | return lua_islightuserdata(luaState, index); 248 | } 249 | 250 | template<> 251 | inline bool check(lua_State* luaState, int index) 252 | { 253 | return lua_istable(luaState, index); 254 | } 255 | 256 | template<> 257 | inline bool check(lua_State* luaState, int index) 258 | { 259 | return lua_isnumber(luaState, index); 260 | } 261 | 262 | template<> 263 | inline bool check(lua_State* luaState, int index) 264 | { 265 | return lua_isnumber(luaState, index); 266 | } 267 | 268 | template<> 269 | inline bool check(lua_State* luaState, int index) 270 | { 271 | lua_State* state = luaState; 272 | bool isCallable = lua_isfunction(state, index) || lua_iscfunction(state, index); 273 | 274 | if (!isCallable) { 275 | lua_getmetatable(state, index); 276 | if (lua_istable(state, -1)) { 277 | lua_pushstring(state, "__call"); 278 | lua_rawget(state, -2); 279 | isCallable = !lua_isnil(state, -1); 280 | lua_pop(state, 1); 281 | } 282 | lua_pop(state, 1); 283 | } 284 | 285 | return isCallable; 286 | } 287 | 288 | ////////////////////////////////////////////////////////////////////////////////////////////// 289 | 290 | template 291 | inline T read(lua_State* luaState, int index); 292 | 293 | template<> 294 | inline int read(lua_State* luaState, int index) { 295 | return lua_tointeger(luaState, index); 296 | } 297 | 298 | template<> 299 | inline long read(lua_State* luaState, int index) { 300 | return static_cast(lua_tointeger(luaState, index)); 301 | } 302 | 303 | template<> 304 | inline long long read(lua_State* luaState, int index) { 305 | return static_cast(lua_tointeger(luaState, index)); 306 | } 307 | 308 | template<> 309 | inline short read(lua_State* luaState, int index) { 310 | return static_cast(lua_tointeger(luaState, index)); 311 | } 312 | 313 | template<> 314 | inline unsigned read(lua_State* luaState, int index) { 315 | #if LUA_VERSION_NUM > 501 316 | return static_cast(lua_tounsigned(luaState, index)); 317 | #else 318 | return static_cast(lua_tointeger(luaState, index)); 319 | #endif 320 | } 321 | 322 | template<> 323 | inline unsigned short read(lua_State* luaState, int index) { 324 | #if LUA_VERSION_NUM > 501 325 | return static_cast(lua_tounsigned(luaState, index)); 326 | #else 327 | return static_cast(lua_tointeger(luaState, index)); 328 | #endif 329 | } 330 | 331 | template<> 332 | inline unsigned long read(lua_State* luaState, int index) { 333 | #if LUA_VERSION_NUM > 501 334 | return static_cast(lua_tounsigned(luaState, index)); 335 | #else 336 | return static_cast(lua_tointeger(luaState, index)); 337 | #endif 338 | } 339 | 340 | template<> 341 | inline unsigned long long read(lua_State* luaState, int index) { 342 | #if LUA_VERSION_NUM > 501 343 | return static_cast(lua_tounsigned(luaState, index)); 344 | #else 345 | return static_cast(lua_tointeger(luaState, index)); 346 | #endif 347 | } 348 | 349 | template<> 350 | inline double read(lua_State* luaState, int index) { 351 | return static_cast(lua_tonumber(luaState, index)); 352 | } 353 | 354 | template<> 355 | inline long double read(lua_State* luaState, int index) { 356 | return static_cast(lua_tonumber(luaState, index)); 357 | } 358 | 359 | template<> 360 | inline float read(lua_State* luaState, int index) { 361 | return static_cast(lua_tonumber(luaState, index)); 362 | } 363 | 364 | template<> 365 | inline bool read(lua_State* luaState, int index) { 366 | return lua_toboolean(luaState, index); 367 | } 368 | 369 | template<> 370 | inline lua::Nil read(lua_State* luaState, int index) { 371 | return nullptr; 372 | } 373 | 374 | template<> 375 | inline lua::Pointer read(lua_State* luaState, int index) { 376 | return lua_touserdata(luaState, index); 377 | } 378 | 379 | template<> 380 | inline char read(lua_State* luaState, int index) { 381 | return static_cast(lua_tostring(luaState, index)[0]); 382 | } 383 | 384 | template<> 385 | inline unsigned char read(lua_State* luaState, int index) { 386 | return static_cast(lua_tostring(luaState, index)[0]); 387 | } 388 | 389 | template<> 390 | inline const char* read(lua_State* luaState, int index) { 391 | return lua_tostring(luaState, index); 392 | } 393 | 394 | template<> 395 | inline std::string read(lua_State* luaState, int index) { 396 | return lua_tostring(luaState, index); 397 | } 398 | 399 | template<> 400 | inline const unsigned char* read(lua_State* luaState, int index) { 401 | return reinterpret_cast(lua_tostring(luaState, index));; 402 | } 403 | 404 | ////////////////////////////////////////////////////////////////////////////////////////////// 405 | 406 | inline void settop(lua_State* luaState, int n) { 407 | LUASTATE_DEBUG_LOG(" POP %d", top(luaState) - n); 408 | lua_settop(luaState, n); 409 | } 410 | 411 | inline void pop(lua_State* luaState, int n) { 412 | LUASTATE_DEBUG_LOG(" POP %d", n); 413 | lua_pop(luaState, n); 414 | } 415 | 416 | template 417 | inline T pop_front(lua_State* luaState) { 418 | T value = read(luaState, 1); 419 | lua_remove(luaState, 0); 420 | return value; 421 | } 422 | 423 | template 424 | inline T pop_back(lua_State* luaState) { 425 | T value = read(luaState, -1); 426 | pop(luaState, 1); 427 | return value; 428 | } 429 | 430 | ////////////////////////////////////////////////////////////////////////////////////////////// 431 | 432 | inline void get(lua_State* luaState, int index) { 433 | LUASTATE_DEBUG_LOG("GET table %d", index); 434 | lua_gettable(luaState, index); 435 | } 436 | 437 | template 438 | inline void get(lua_State* luaState, int index, T key) {} 439 | 440 | template<> 441 | inline void get(lua_State* luaState, int index, const char* key) { 442 | LUASTATE_DEBUG_LOG("GET %s", key); 443 | lua_getfield(luaState, index, key); 444 | } 445 | 446 | template<> 447 | inline void get(lua_State* luaState, int index, int key) { 448 | LUASTATE_DEBUG_LOG("GET %d", key); 449 | lua_rawgeti(luaState, index, key); 450 | } 451 | 452 | inline void get_global(lua_State* luaState, const char* name) { 453 | LUASTATE_DEBUG_LOG("GET_GLOBAL %s", name); 454 | lua_getglobal(luaState, name); 455 | } 456 | 457 | }} 458 | -------------------------------------------------------------------------------- /include/LuaStackItem.h: -------------------------------------------------------------------------------- 1 | // 2 | // 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 06/05/14. 6 | // 7 | // 8 | 9 | #pragma once 10 | 11 | #include 12 | 13 | namespace lua { namespace detail { 14 | 15 | ////////////////////////////////////////////////////////////////////////////////////////////// 16 | struct DeallocStackItem { 17 | int stackCap; 18 | int numElements; 19 | 20 | DeallocStackItem(int stackTop, int numElements) : stackCap(stackTop + numElements), numElements(numElements) {} 21 | }; 22 | 23 | ////////////////////////////////////////////////////////////////////////////////////////////// 24 | struct DeallocStackComparison { 25 | bool operator() (const DeallocStackItem& lhs, const DeallocStackItem& rhs) const { 26 | return lhs.stackCap < rhs.stackCap; 27 | } 28 | }; 29 | 30 | ////////////////////////////////////////////////////////////////////////////////////////////// 31 | typedef std::priority_queue, DeallocStackComparison> DeallocQueue; 32 | 33 | ////////////////////////////////////////////////////////////////////////////////////////////// 34 | struct StackItem { 35 | 36 | lua_State* state; 37 | detail::DeallocQueue* deallocQueue; 38 | 39 | /// Indicates number of pushed values to stack on lua::Value when created 40 | int top; 41 | 42 | /// Indicates number pushed values which were pushed by this lua::Value instance 43 | mutable int pushed; 44 | 45 | /// Indicates multi returned values, because the we want first returned value and not the last 46 | int grouped; 47 | 48 | StackItem() : state(nullptr), deallocQueue(nullptr) 49 | { 50 | } 51 | 52 | StackItem(lua_State* luaState, detail::DeallocQueue* deallocQueue, int stackTop, int pushedValues, int groupedValues) 53 | : state(luaState) 54 | , deallocQueue(deallocQueue) 55 | , top(stackTop) 56 | , pushed(pushedValues) 57 | , grouped(groupedValues) 58 | { 59 | } 60 | 61 | ~StackItem() 62 | { 63 | // Check if stack is managed automaticaly (_deallocQueue == nullptr), which is when we call C functions from Lua 64 | if (deallocQueue != nullptr) { 65 | 66 | // Check if we dont try to release same values twice 67 | int currentStackTop = stack::top(state); 68 | if (currentStackTop < pushed + top) { 69 | return; 70 | } 71 | 72 | // We will check if we haven't pushed some other new lua::Value to stack 73 | if (top + pushed == currentStackTop) { 74 | 75 | // We will check deallocation priority queue, if there are some lua::Value instances to be deleted 76 | while (!deallocQueue->empty() && deallocQueue->top().stackCap == top) { 77 | top -= deallocQueue->top().numElements; 78 | deallocQueue->pop(); 79 | } 80 | stack::settop(state, top); 81 | } 82 | // If yes we can't pop values, we must pop it after deletion of newly created lua::Value 83 | // We will put this deallocation to our priority queue, so it will be deleted as soon as possible 84 | else 85 | deallocQueue->push(detail::DeallocStackItem(top, pushed)); 86 | } 87 | } 88 | }; 89 | } } -------------------------------------------------------------------------------- /include/LuaState.h: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////////////////////////////////// 2 | // 3 | // LuaState.h 4 | // LuaState 5 | // 6 | // Created by Simon Mikuda on 18/03/14. 7 | // 8 | // See LICENSE and README.md files 9 | ////////////////////////////////////////////////////////////////////////////////////////////// 10 | 11 | #pragma once 12 | 13 | // Compatibility with non-clang compilers. 14 | #ifndef __has_feature 15 | # define __has_feature(x) 0 16 | #endif 17 | 18 | #ifdef LUASTATE_DEBUG_MODE 19 | # define LUASTATE_DEBUG_LOG(format, ...) printf(format "\n", ## __VA_ARGS__) 20 | # define LUASTATE_ASSERT(condition) assert(condition) 21 | #else 22 | # define LUASTATE_DEBUG_LOG(format, ...) 23 | # define LUASTATE_ASSERT(condition) 24 | #endif 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include 35 | 36 | #include "./Traits.h" 37 | 38 | #include "./LuaPrimitives.h" 39 | #include "./LuaStack.h" 40 | #include "./LuaException.h" 41 | #include "./LuaStackItem.h" 42 | #include "./LuaValue.h" 43 | #include "./LuaReturn.h" 44 | #include "./LuaFunctor.h" 45 | #include "./LuaRef.h" 46 | 47 | namespace lua { 48 | 49 | ////////////////////////////////////////////////////////////////////////////////////////////// 50 | /// Class that hold lua interpreter state. Lua state is managed by pointer which also is copied to lua::Ref values. 51 | class State 52 | { 53 | /// Class takes care of automaticaly closing Lua state when in destructor 54 | lua_State* _luaState; 55 | 56 | /// Class deletes DeallocQueue in destructor 57 | detail::DeallocQueue* _deallocQueue; 58 | 59 | /// Function for metatable "__call" field. It calls stored functor pushes return values to stack. 60 | /// 61 | /// @pre In Lua C API during function calls lua_State moves stack index to place, where first element is our userdata, and next elements are returned values 62 | static int metatableCallFunction(lua_State* luaState) { 63 | BaseFunctor* functor = *(BaseFunctor **)luaL_checkudata(luaState, 1, "luaL_Functor");; 64 | return functor->call(luaState); 65 | } 66 | 67 | /// Function for metatable "__gc" field. It deletes captured variables from stored functors. 68 | static int metatableDeleteFunction(lua_State* luaState) { 69 | BaseFunctor* functor = *(BaseFunctor **)luaL_checkudata(luaState, 1, "luaL_Functor");; 70 | delete functor; 71 | return 0; 72 | } 73 | 74 | lua::Value executeLoadedFunction(int index) const { 75 | // bool executed; 76 | // try { 77 | // executed = lua_pcall(_luaState, 0, LUA_MULTRET, 0) == 0; 78 | // } catch (lua::TypeMismatchError ex) { 79 | // throw ex; 80 | // } 81 | // 82 | // if (!executed) 83 | if (lua_pcall(_luaState, 0, LUA_MULTRET, 0)) 84 | throw RuntimeError(_luaState); 85 | 86 | int pushedValues = stack::top(_luaState) - index; 87 | return lua::Value(std::make_shared(_luaState, _deallocQueue, index, pushedValues, pushedValues > 0 ? pushedValues - 1 : 0)); 88 | } 89 | 90 | void initialize(bool loadLibs) { 91 | _deallocQueue = new detail::DeallocQueue(); 92 | _luaState = luaL_newstate(); 93 | assert(_luaState != nullptr); 94 | 95 | if (loadLibs) 96 | luaL_openlibs(_luaState); 97 | 98 | 99 | // We will create metatable for Lua functors for memory management and actual function call 100 | luaL_newmetatable(_luaState, "luaL_Functor"); 101 | 102 | // Set up metatable call operator for functors 103 | lua_pushcfunction(_luaState, &State::metatableCallFunction); 104 | lua_setfield(_luaState, -2, "__call"); 105 | 106 | // Set up metatable garbage collection for functors 107 | lua_pushcfunction(_luaState, &State::metatableDeleteFunction); 108 | lua_setfield(_luaState, -2, "__gc"); 109 | 110 | // Pop metatable 111 | lua_pop(_luaState, 1); 112 | } 113 | 114 | public: 115 | 116 | /// Constructor creates new state and stores it to pointer. 117 | /// 118 | /// @param loadLibs If we want to open standard libraries - function luaL_openlibs 119 | State(bool loadLibs) { initialize(loadLibs); } 120 | 121 | /// Constructor creates new state stores it to pointer and loads standard libraries 122 | State() { initialize(true); } 123 | 124 | ~State() { 125 | lua_close(_luaState); 126 | delete _deallocQueue; 127 | } 128 | 129 | // State is non-copyable 130 | State(const State& other) = delete; 131 | State& operator=(const State&) = delete; 132 | 133 | /// Query global values from Lua state 134 | /// 135 | /// @return Some value with type lua::Type 136 | Value operator[](lua::String name) const { 137 | return Value(_luaState, _deallocQueue, name); 138 | } 139 | 140 | /// Deleted compare operator 141 | bool operator==(Value &other) = delete; 142 | 143 | /// Sets global value to Lua state 144 | /// 145 | /// @param key Stores value to _G[key] 146 | /// @param value Value witch will be stored to _G[key] 147 | template 148 | void set(lua::String key, T value) const { 149 | stack::push(_luaState, std::forward(value)); 150 | lua_setglobal(_luaState, key); 151 | } 152 | 153 | /// Executes file text on Lua state 154 | /// 155 | /// @throws lua::LoadError When file cannot be found or loaded 156 | /// @throws lua::RuntimeError When there is runtime error 157 | /// 158 | /// @param filePath File path indicating which file will be executed 159 | lua::Value doFile(const std::string& filePath) const { 160 | int stackTop = stack::top(_luaState); 161 | 162 | if (luaL_loadfile(_luaState, filePath.c_str())) 163 | throw LoadError(_luaState); 164 | 165 | return executeLoadedFunction(stackTop); 166 | } 167 | 168 | /// Execute string on Lua state 169 | /// 170 | /// @throws lua::LoadError When string cannot be loaded 171 | /// @throws lua::RuntimeError When there is runtime error 172 | /// 173 | /// @param string Command which will be executed 174 | lua::Value doString(const std::string& string) const { 175 | int stackTop = stack::top(_luaState); 176 | 177 | if (luaL_loadstring(_luaState, string.c_str())) 178 | throw LoadError(_luaState); 179 | 180 | return executeLoadedFunction(stackTop); 181 | } 182 | 183 | #ifdef LUASTATE_DEBUG_MODE 184 | 185 | /// Flush all elements from stack and check ref counting 186 | void checkMemLeaks() { 187 | 188 | bool noLeaks = true; 189 | 190 | // Check if there are any values from stack, should be zero 191 | int count = stack::top(_luaState); 192 | if (count != 0) { 193 | LUASTATE_DEBUG_LOG("There are %d elements in stack:", count); 194 | stack::dump(_luaState); 195 | noLeaks = false; 196 | } 197 | 198 | // Dealloc queue should be empty 199 | if (!_deallocQueue->empty()) { 200 | LUASTATE_DEBUG_LOG("Deallocation queue has %lu elements:", _deallocQueue->size()); 201 | while (!_deallocQueue->empty()) { 202 | LUASTATE_DEBUG_LOG("[stackCap = %d, numElements = %d]", _deallocQueue->top().stackCap, _deallocQueue->top().numElements); 203 | _deallocQueue->pop(); 204 | } 205 | noLeaks = false; 206 | } 207 | assert(noLeaks); 208 | } 209 | 210 | void stackDump() const { 211 | lua::stack::dump(_luaState); 212 | } 213 | #endif 214 | 215 | /// Get pointer of Lua state 216 | /// 217 | /// @return Pointer of Lua state 218 | lua_State* getState() { return _luaState; } 219 | 220 | 221 | ////////////////////////////////////////////////////////////////////////////////////////////// 222 | // Conventional setting functions 223 | 224 | void setCStr(lua::String key, const char* value) const { 225 | set(key, value); 226 | } 227 | 228 | void setData(lua::String key, const char* value, size_t length) const { 229 | stack::push_str(_luaState, value, length); 230 | lua_setglobal(_luaState, key); 231 | } 232 | 233 | void setString(lua::String key, const std::string& string) const { 234 | setData(key, string.c_str(), string.length()); 235 | } 236 | 237 | void set(lua::String key, const std::string& value) const { 238 | setString(key, value); 239 | } 240 | 241 | void setNumber(lua::String key, lua::Number number) const { 242 | set(key, number); 243 | } 244 | 245 | void setInt(lua::String key, int number) const { 246 | set(key, number); 247 | } 248 | 249 | void setUnsigned(lua::String key, unsigned number) const { 250 | set(key, number); 251 | } 252 | 253 | void setFloat(lua::String key, float number) const { 254 | set(key, number); 255 | } 256 | 257 | void setDouble(lua::String key, double number) const { 258 | set(key, number); 259 | } 260 | }; 261 | } 262 | -------------------------------------------------------------------------------- /include/LuaValue.h: -------------------------------------------------------------------------------- 1 | // 2 | // LuaValue.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 17/03/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #pragma once 10 | 11 | namespace lua { 12 | 13 | class Value; 14 | class State; 15 | class Ref; 16 | template class Return; 17 | 18 | ////////////////////////////////////////////////////////////////////////////////////////////// 19 | /// This is class for: 20 | /// * querying values from lua tables, 21 | /// * setting values to lua tables, 22 | /// * calling values as functions, 23 | /// * checking value type. 24 | class Value 25 | { 26 | friend class State; 27 | friend class Ref; 28 | template friend class Return; 29 | 30 | std::shared_ptr _stack; 31 | 32 | /// Constructor for lua::State class. Whill get global in _G table with name 33 | /// 34 | /// @param luaState Pointer of Lua state 35 | /// @param deallocQueue Queue for deletion values initialized from given luaState 36 | /// @param name Key of global value 37 | Value(lua_State* luaState, detail::DeallocQueue* deallocQueue, const char* name) 38 | : _stack(std::make_shared(luaState, deallocQueue, stack::top(luaState), 1, 0)) 39 | { 40 | stack::get_global(_stack->state, name); 41 | } 42 | 43 | template 44 | void callFunction(bool protectedCall, Ts... args) const { 45 | 46 | // Function must be on top of stack 47 | LUASTATE_ASSERT(stack::check(_stack->state, stack::top(_stack->state))); 48 | 49 | stack::push(_stack->state, args...); 50 | 51 | if (protectedCall) { 52 | if (lua_pcall(_stack->state, sizeof...(Ts), LUA_MULTRET, 0)) 53 | throw RuntimeError(_stack->state); 54 | } 55 | else 56 | lua_call(_stack->state, sizeof...(Ts), LUA_MULTRET); 57 | } 58 | 59 | template 60 | Value executeFunction(bool protectedCall, Ts... args) const { 61 | 62 | int stackTop = stack::top(_stack->state); 63 | 64 | // We will duplicate Lua function value, because it will get poped from stack 65 | lua_pushvalue(_stack->state, _stack->top + _stack->pushed - _stack->grouped); 66 | 67 | callFunction(protectedCall, args...); 68 | int returnedValues = stack::top(_stack->state) - stackTop; 69 | 70 | LUASTATE_ASSERT(returnedValues >= 0); 71 | 72 | return Value(std::make_shared(_stack->state, _stack->deallocQueue, stackTop, returnedValues, returnedValues == 0 ? 0 : returnedValues - 1)); 73 | } 74 | 75 | template 76 | Value&& executeFunction(bool protectedCall, Ts... args) { 77 | 78 | int stackTop = stack::top(_stack->state); 79 | 80 | // we check if there are not pushed values before function 81 | if (_stack->top + _stack->pushed < stackTop) { 82 | 83 | _stack->deallocQueue->push(detail::DeallocStackItem(_stack->top, _stack->pushed)); 84 | 85 | lua_pushvalue(_stack->state, _stack->top + 1); 86 | 87 | _stack->top = stackTop; 88 | _stack->pushed = 1; 89 | _stack->grouped = 0; 90 | 91 | ++stackTop; 92 | } 93 | 94 | // StackItem top must same as top of current stack 95 | LUASTATE_ASSERT(_stack->top + _stack->pushed == stack::top(_stack->state)); 96 | 97 | callFunction(protectedCall, args...); 98 | 99 | _stack->grouped = stack::top(_stack->state) - stackTop; 100 | _stack->pushed += _stack->grouped; 101 | 102 | LUASTATE_ASSERT(_stack->pushed >= 0); 103 | 104 | return std::move(*this); 105 | } 106 | 107 | public: 108 | 109 | /// Enable to initialize empty Value, so we can set it up later 110 | Value() : _stack(nullptr) { 111 | } 112 | 113 | /// Constructor for returning values from functions and for creating lua::Ref instances 114 | /// 115 | /// @param stackItem Prepared stack item 116 | Value(std::shared_ptr&& stackItem) 117 | : _stack(stackItem) 118 | { 119 | } 120 | 121 | /// With this function we will create lua::Ref instance 122 | /// 123 | /// @note This function doesn't check if current value is lua::Table. You must use is() function if you want to be sure 124 | template 125 | Value operator[](T key) const { 126 | stack::get(_stack->state, _stack->top + _stack->pushed - _stack->grouped, key); 127 | return Value(std::make_shared(_stack->state, _stack->deallocQueue, stack::top(_stack->state) - 1, 1, 0)); 128 | } 129 | 130 | #if __has_feature(cxx_reference_qualified_functions) 131 | 132 | /// While chaining [] operators we will call this function multiple times and can query nested tables. 133 | /// 134 | /// @note This function doesn't check if current value is lua::Table. You must use is() function if you want to be sure 135 | template 136 | Value&& operator[](T key) && { 137 | stack::get(_stack->state, _stack->top + _stack->pushed - _stack->grouped, key); 138 | ++_stack->pushed; 139 | 140 | _stack->grouped = 0; 141 | 142 | return std::forward(*this); 143 | } 144 | 145 | #endif 146 | 147 | /// Call given value. 148 | /// 149 | /// @note This function doesn't check if current value is lua::Callable. You must use is() function if you want to be sure 150 | template 151 | Value operator()(Ts... args) const { 152 | return executeFunction(false, args...); 153 | } 154 | 155 | /// Protected call of given value. 156 | /// 157 | /// @note This function doesn't check if current value is lua::Callable. You must use is() function if you want to be sure 158 | template 159 | Value call(Ts... args) const { 160 | return executeFunction(true, args...); 161 | } 162 | 163 | #if __has_feature(cxx_reference_qualified_functions) 164 | 165 | /// Call given value. 166 | /// 167 | /// @note This function doesn't check if current value is lua::Callable. You must use is() function if you want to be sure 168 | template 169 | Value&& operator()(Ts... args) && { 170 | return executeFunction(false, args...); 171 | } 172 | 173 | /// Protected call of given value. 174 | /// 175 | /// @note This function doesn't check if current value is lua::Callable. You must use is() function if you want to be sure 176 | template 177 | Value&& call(Ts... args) && { 178 | return executeFunction(true, args...); 179 | } 180 | 181 | #endif 182 | 183 | template 184 | T to() const { 185 | return std::forward(stack::read(_stack->state, _stack->top + _stack->pushed - _stack->grouped)); 186 | } 187 | 188 | /// Cast operator. Enables to pop values from stack and store it to variables 189 | /// 190 | /// @return Any value of type from LuaPrimitives.h 191 | template 192 | operator T() const { 193 | return to(); 194 | } 195 | 196 | /// Set values to table to the given key. 197 | /// 198 | /// @param key Key to which value will be stored 199 | /// @param value Value to be stored to table on given key 200 | /// 201 | /// @note This function doesn't check if current value is lua::Table. You must use is() function if you want to be sure 202 | template 203 | void set(K key, T value) const { 204 | stack::push(_stack->state, key); 205 | stack::push(_stack->state, std::forward(value)); 206 | lua_settable(_stack->state, _stack->top + _stack->pushed - _stack->grouped); 207 | } 208 | 209 | /// Check if queryied value is some type from LuaPrimitives.h file 210 | /// 211 | /// @return true if yes false if no 212 | template 213 | bool is() const { 214 | return stack::check(_stack->state, _stack->top + _stack->pushed - _stack->grouped); 215 | } 216 | 217 | /// First check if lua::Value is type T and if yes stores it to value 218 | /// 219 | /// @param value Reference to variable where will be stored result if types are right 220 | /// 221 | /// @return true if value was given type and stored to value false if not 222 | template 223 | bool get(T& value) const { 224 | if (is() == false) 225 | return false; 226 | else { 227 | value = stack::read(_stack->state, _stack->top + _stack->pushed - _stack->grouped); 228 | return true; 229 | } 230 | } 231 | 232 | /// @returns Value position on stack 233 | int getStackIndex() const { 234 | assert(_stack->pushed > 0); 235 | return _stack->top + 1; 236 | } 237 | 238 | ////////////////////////////////////////////////////////////////////////////////////////////// 239 | // Conventional conversion functions 240 | 241 | // to 242 | 243 | const char* toCStr() const { 244 | return to(); 245 | } 246 | 247 | std::string toString() const { 248 | return to(); 249 | } 250 | 251 | lua::Number toNumber() const { 252 | return to(); 253 | } 254 | 255 | int toInt() const { 256 | return to(); 257 | } 258 | 259 | unsigned toUnsigned() const { 260 | return to(); 261 | } 262 | 263 | float toFloat() const { 264 | return to(); 265 | } 266 | 267 | double toDouble() const { 268 | return to(); 269 | } 270 | 271 | /// Will get pointer casted to given template type 272 | /// 273 | /// @return Pointer staticaly casted to given template type 274 | template 275 | T* toPtr() const { 276 | return static_cast(Pointer(*this)); 277 | } 278 | 279 | // get 280 | 281 | bool getCStr(const char*& cstr) const { 282 | return get(cstr); 283 | } 284 | 285 | bool getString(std::string& string) const { 286 | lua::String cstr; 287 | bool success = get(cstr); 288 | 289 | if (success) 290 | string = cstr; 291 | 292 | return success; 293 | } 294 | 295 | bool getNumber(lua::Number number) const { 296 | return get(number); 297 | } 298 | 299 | bool getInt(int number) const { 300 | return get(number); 301 | } 302 | 303 | bool getUnsigned(unsigned number) const { 304 | return get(number); 305 | } 306 | 307 | bool getFloat(float number) const { 308 | return get(number); 309 | } 310 | 311 | bool getDouble(double number) const { 312 | return get(number); 313 | } 314 | 315 | template 316 | T* getPtr(T*& pointer) const { 317 | lua::Pointer cptr; 318 | bool success = get(cptr); 319 | 320 | if (success) 321 | pointer = static_cast(Pointer(*this)); 322 | 323 | return success; 324 | } 325 | 326 | ////////////////////////////////////////////////////////////////////////////////////////////// 327 | // Conventional setting functions 328 | 329 | template 330 | void setCStr(K key, const char* value) const { 331 | set(key, value); 332 | } 333 | 334 | template 335 | void setData(K key, const char* value, size_t length) const { 336 | stack::push(_stack->state, key); 337 | stack::push_str(_stack->state, value, length); 338 | lua_settable(_stack->state, _stack->top + _stack->pushed - _stack->grouped); 339 | } 340 | 341 | template 342 | void setString(K key, const std::string& string) const { 343 | stack::push(_stack->state, key); 344 | stack::push_str(_stack->state, string.c_str(), string.length()); 345 | lua_settable(_stack->state, _stack->top + _stack->pushed - _stack->grouped); 346 | } 347 | 348 | int length() const { 349 | #if LUA_VERSION_NUM > 501 350 | return lua_rawlen(_stack->state, _stack->top + _stack->pushed - _stack->grouped); 351 | #else 352 | return lua_objlen(_stack->state, _stack->top + _stack->pushed - _stack->grouped); 353 | #endif 354 | } 355 | 356 | template 357 | void set(K key, const std::string& value) const { 358 | setString(key, value); 359 | } 360 | 361 | template 362 | void setNumber(K key, lua::Number number) const { 363 | set(key, number); 364 | } 365 | 366 | template 367 | void setInt(K key, int number) const { 368 | set(key, number); 369 | } 370 | 371 | template 372 | void setUnsigned(K key, unsigned number) const { 373 | set(key, number); 374 | } 375 | 376 | template 377 | void setFloat(K key, float number) const { 378 | set(key, number); 379 | } 380 | 381 | template 382 | void setDouble(K key, double number) const { 383 | set(key, number); 384 | } 385 | 386 | }; 387 | 388 | // compare operators 389 | ////////////////////////////////////////////////////////////////////////////////////////////// 390 | 391 | template 392 | inline bool operator==(const Value &stateValue, const T& value) { 393 | return T(stateValue) == value; 394 | } 395 | template 396 | inline bool operator==(const T& value, const Value &stateValue) { 397 | return T(stateValue) == value; 398 | } 399 | 400 | template 401 | inline bool operator!=(const Value &stateValue, const T& value) { 402 | return T(stateValue) != value; 403 | } 404 | template 405 | inline bool operator!=(const T& value, const Value &stateValue) { 406 | return T(stateValue) != value; 407 | } 408 | 409 | template 410 | inline bool operator<(const Value &stateValue, const T& value) { 411 | return T(stateValue) < value; 412 | } 413 | template 414 | inline bool operator<(const T& value, const Value &stateValue) { 415 | return T(stateValue) < value; 416 | } 417 | 418 | template 419 | inline bool operator<=(const Value &stateValue, const T& value) { 420 | return T(stateValue) <= value; 421 | } 422 | template 423 | inline bool operator<=(const T& value, const Value &stateValue) { 424 | return T(stateValue) <= value; 425 | } 426 | 427 | template 428 | inline bool operator>(const Value &stateValue, const T& value) { 429 | return T(stateValue) > value; 430 | } 431 | template 432 | inline bool operator>(const T& value, const Value &stateValue) { 433 | return T(stateValue) > value; 434 | } 435 | 436 | template 437 | inline bool operator>=(const Value &stateValue, const T& value) { 438 | return T(stateValue) >= value; 439 | } 440 | template 441 | inline bool operator>=(const T& value, const Value &stateValue) { 442 | return T(stateValue) >= value; 443 | } 444 | 445 | 446 | 447 | 448 | inline bool operator==(const Value &stateValue, const std::string& value) { 449 | return lua::String(stateValue) == value; 450 | } 451 | inline bool operator==(const std::string& value, const Value &stateValue) { 452 | return lua::String(stateValue) == value; 453 | } 454 | 455 | inline bool operator!=(const Value &stateValue, const std::string& value) { 456 | return lua::String(stateValue) != value; 457 | } 458 | inline bool operator!=(const std::string& value, const Value &stateValue) { 459 | return lua::String(stateValue) != value; 460 | } 461 | 462 | inline bool operator<(const Value &stateValue, const std::string& value) { 463 | return lua::String(stateValue) < value; 464 | } 465 | inline bool operator<(const std::string& value, const Value &stateValue) { 466 | return lua::String(stateValue) < value; 467 | } 468 | 469 | inline bool operator<=(const Value &stateValue, const std::string& value) { 470 | return lua::String(stateValue) <= value; 471 | } 472 | inline bool operator<=(const std::string& value, const Value &stateValue) { 473 | return lua::String(stateValue) <= value; 474 | } 475 | 476 | inline bool operator>(const Value &stateValue, const std::string& value) { 477 | return lua::String(stateValue) > value; 478 | } 479 | inline bool operator>(const std::string& value, const Value &stateValue) { 480 | return lua::String(stateValue) > value; 481 | } 482 | 483 | inline bool operator>=(const Value &stateValue, const std::string& value) { 484 | return lua::String(stateValue) >= value; 485 | } 486 | inline bool operator>=(const std::string& value, const Value &stateValue) { 487 | return lua::String(stateValue) >= value; 488 | } 489 | 490 | 491 | namespace stack { 492 | 493 | template<> 494 | inline bool check(lua_State* luaState, int index) 495 | { 496 | return true; 497 | } 498 | 499 | /// Values direct forwarding 500 | template<> 501 | inline int push(lua_State* luaState, lua::Value value) { 502 | lua_pushvalue(luaState, value.getStackIndex()); 503 | return 1; 504 | } 505 | 506 | } 507 | } 508 | 509 | -------------------------------------------------------------------------------- /include/Traits.h: -------------------------------------------------------------------------------- 1 | // 2 | // Traits.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 22/03/14. 6 | // 7 | // See LICENSE and README.md files// 8 | 9 | #pragma once 10 | 11 | namespace lua { namespace traits { 12 | 13 | ////////////////////////////////////////////////////////////////////////////////////////////// 14 | 15 | template 16 | struct function_traits 17 | : public function_traits 18 | {}; 19 | 20 | template 21 | struct function_traits 22 | { 23 | enum { arity = sizeof...(Args) }; 24 | 25 | typedef ReturnType ResultType; 26 | typedef std::function Function; 27 | 28 | template 29 | struct Arg { 30 | typedef typename std::tuple_element>::type Type; 31 | }; 32 | }; 33 | 34 | ////////////////////////////////////////////////////////////////////////////////////////////// 35 | 36 | template struct index_tuple{}; 37 | 38 | template 39 | struct make_indexes_impl; 40 | 41 | template 42 | struct make_indexes_impl, T, Types...> 43 | { 44 | typedef typename make_indexes_impl, Types...>::type type; 45 | }; 46 | 47 | template 48 | struct make_indexes_impl > 49 | { 50 | typedef index_tuple type; 51 | }; 52 | 53 | template 54 | struct make_indexes : make_indexes_impl<0, index_tuple<>, Types...> 55 | {}; 56 | 57 | ////////////////////////////////////////////////////////////////////////////////////////////// 58 | 59 | template 60 | Ret apply_helper(std::function pf, index_tuple< Indexes... >, std::tuple&& tup) 61 | { 62 | return pf( std::forward( std::get(tup))... ); 63 | } 64 | 65 | template 66 | Ret apply(std::function pf, const std::tuple& tup) 67 | { 68 | return apply_helper(pf, typename make_indexes::type(), std::tuple(tup)); 69 | } 70 | 71 | template 72 | Ret apply(std::function pf, std::tuple&& tup) 73 | { 74 | return apply_helper(pf, typename make_indexes::type(), std::forward>(tup)); 75 | } 76 | 77 | template 78 | void apply_no_ret(std::function pf, const std::tuple& tup) 79 | { 80 | apply_helper(pf, typename make_indexes::type(), std::tuple(tup)); 81 | } 82 | 83 | template 84 | void apply_no_ret(std::function pf, std::tuple&& tup) 85 | { 86 | apply_helper(pf, typename make_indexes::type(), std::forward>(tup)); 87 | } 88 | 89 | ////////////////////////////////////////////////////////////////////////////////////////////// 90 | 91 | template 92 | struct indexes {}; 93 | 94 | template 95 | struct indexes_builder : indexes_builder {}; 96 | 97 | template 98 | struct indexes_builder<0, Is...> { 99 | typedef indexes index; 100 | }; 101 | }} -------------------------------------------------------------------------------- /test/get_test.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // get_tests.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 16/04/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | 10 | #include "test.h" 11 | 12 | ////////////////////////////////////////////////////////////////////////////////////////////// 13 | int main(int argc, char** argv) 14 | { 15 | // We create state and variables 16 | lua::State state; 17 | state.doString(createVariables); 18 | state.doString(createFunctions); 19 | 20 | // Test indexes 21 | assert(state["table"][1] == 100); 22 | assert(strcmp(state["table"][2], "hello") == 0); 23 | assert(state["table"][3] == true); 24 | 25 | // Test fields 26 | assert(state["table"]["one"] == 1); 27 | assert(state["table"]["two"] == 2); 28 | assert(state["table"]["three"] == 3); 29 | 30 | assert(state["table"]["a"] == 'a'); 31 | assert(state["table"]["b"] == 'b'); 32 | assert(state["table"]["c"] == 'c'); 33 | 34 | // Test nesting tables 35 | assert(state["nested"]["table"]["one"] == 1); 36 | assert(state["nested"]["nested"]["table"]["two"] == 2); 37 | assert(state["nested"]["nested"]["nested"]["table"]["three"] == 3); 38 | 39 | assert(state["nested"]["nested"]["nested"]["nested"]["table"]["a"] == 'a'); 40 | assert(state["nested"]["nested"]["table"]["b"] == 'b'); 41 | assert(state["nested"]["nested"]["nested"]["nested"]["nested"]["nested"]["table"]["c"] == 'c'); 42 | 43 | // Test function return values 44 | assert(state["getInteger"]() == 10); 45 | assert(state["getValues"]() == 1); 46 | 47 | // Test function multi return values 48 | int a, b, c, d; 49 | lua::tie(a) = state["getValues"](); 50 | assert(a == 1); 51 | lua::tie(a, b) = state["getValues"](); 52 | assert(a == 1 && b == 2); 53 | lua::tie(a, b, c) = state["getValues"](); 54 | assert(a == 1 && b == 2 && c == 3); 55 | lua::tie(a, b, c, d) = state["getValues"](); 56 | assert(a == 1 && b == 2 && c == 3); 57 | 58 | // Test mixed nesting 59 | assert(state["getTable"]()[1] == 100); 60 | assert(state["getTable"]()["a"] == 'a'); 61 | 62 | assert(state["getNested"]()["func"]()["func"]()["func"]()["table"][1] == 100); 63 | assert(state["getNested"]()["func"]()["func"]()["func"]()["table"]["a"] == 'a'); 64 | 65 | // Test mixed nesting with multi return 66 | assert(state["getNestedValues"]() == 1); 67 | 68 | { 69 | lua::Value test; 70 | lua::tie(a, test, c) = state["getNestedValues"](); 71 | assert(a == 1 && c == 3); 72 | assert(test[1] == 1); 73 | assert(test[2] == 2); 74 | assert(test[3] == 3); 75 | } 76 | 77 | // Test get function 78 | lua::Integer integerValue; 79 | lua::Number numberValue; 80 | lua::String stringValue; 81 | lua::Boolean boolValue = false; 82 | 83 | if (state["integer"].get(stringValue)) 84 | assert(false); 85 | if (state["integer"].get(integerValue)) 86 | assert(integerValue == 10); 87 | else 88 | assert(false); 89 | 90 | if (state["text"].get(integerValue)) 91 | assert(false); 92 | if (state["text"].get(stringValue)) 93 | assert(strcmp(stringValue, "hello") == 0); 94 | else 95 | assert(false); 96 | 97 | if (state["boolean"].get(stringValue)) 98 | assert(false); 99 | if (state["boolean"].get(boolValue)) 100 | assert(boolValue == true); 101 | else 102 | assert(false); 103 | 104 | if (state["number"].get(stringValue)) 105 | assert(false); 106 | if (state["number"].get(integerValue)) 107 | assert(false); 108 | if (state["number"].get(numberValue)) 109 | assert(numberValue == 2.5); 110 | else 111 | assert(false); 112 | 113 | state.checkMemLeaks(); 114 | 115 | return 0; 116 | } 117 | -------------------------------------------------------------------------------- /test/lambda_test.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // state_tests.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 16/04/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #include "test.h" 10 | 11 | using namespace std::placeholders; 12 | 13 | ////////////////////////////////////////////////////////////////////////////////////////////// 14 | const char* getHello() 15 | { 16 | return "Hello return\n"; 17 | } 18 | 19 | int subValues(int a, int b) 20 | { 21 | return a - b; 22 | } 23 | 24 | ////////////////////////////////////////////////////////////////////////////////////////////// 25 | struct Resource { 26 | static int refCounter; 27 | 28 | Resource() { 29 | ++refCounter; 30 | } 31 | 32 | ~Resource() { 33 | --refCounter; 34 | } 35 | }; 36 | int Resource::refCounter = 0; 37 | 38 | ////////////////////////////////////////////////////////////////////////////////////////////// 39 | struct Foo { 40 | int a; int b; 41 | 42 | void setB(int value) { b = value; } 43 | 44 | Foo(lua::State& state) { 45 | 46 | state.set("Foo_setA", [this](int value) { a = value; } ); 47 | state.set("Foo_setB", std::function(std::bind(&Foo::setB, this, _1)) ); 48 | } 49 | }; 50 | 51 | ////////////////////////////////////////////////////////////////////////////////////////////// 52 | int main(int argc, char** argv) 53 | { 54 | // Create Lua state 55 | lua::State state; 56 | 57 | int intValue; 58 | lua::String cText; 59 | 60 | // Test normal function bind 61 | state.set("lambda", &getHello); 62 | assert(strcmp(state["lambda"](), getHello()) == 0); 63 | 64 | // Test lambda captures 65 | bool flag = false; 66 | state.set("lambda", [&flag]() { flag = true; } ); 67 | state.doString("lambda()"); 68 | assert(flag == true); 69 | 70 | // Test function and lambda arguments 71 | state.set("lambda", &subValues); 72 | assert(state["lambda"](8, 5) == 3); 73 | 74 | state.set("lambda", [](int a, int b, int c, int d) -> int { 75 | return a + b + c + d; 76 | }); 77 | state.doString("a = lambda(4, 8, 12, 14)"); 78 | assert(state["a"] == 38); 79 | 80 | // Test direct passing to functions 81 | { 82 | lua::Value value = state["lambda"]; 83 | assert(value(state["a"], 1, 0, 1) == 40); 84 | assert(value(1, state["a"], 0, 1) == 40); 85 | assert(value(1, 0, state["a"], 1) == 40); 86 | assert(value(1, 0, 1, state["a"]) == 40); 87 | assert(value(state["a"], state["a"], state["a"], state["a"]) == 152); 88 | } 89 | 90 | assert(state["lambda"](state["a"], 1, 0, 1) == 40); 91 | assert(state["lambda"](1, state["a"], 0, 1) == 40); 92 | assert(state["lambda"](1, 0, state["a"], 1) == 40); 93 | assert(state["lambda"](1, 0, 1, state["a"]) == 40); 94 | assert(state["lambda"](state["a"], state["a"], state["a"], state["a"]) == 152); 95 | 96 | // Test when we provide less arguments than we need 97 | state.set("lambda", [&intValue](lua::Value a, lua::Value b, lua::Value c, lua::Value d) { 98 | intValue = 99 | (a.is() ? a : 0) + 100 | (b.is() ? b : 0) + 101 | (c.is() ? c : 0) + 102 | (d.is() ? d : 0); 103 | }); 104 | state.doString("lambda()"); 105 | assert(intValue == 0); 106 | state.doString("lambda(5)"); 107 | assert(intValue == 5); 108 | state.doString("lambda(4, 8)"); 109 | assert(intValue == 12); 110 | state.doString("lambda(1, 2, 3)"); 111 | assert(intValue == 6); 112 | state.doString("lambda(1, 2, 3, 4)"); 113 | assert(intValue == 10); 114 | { 115 | lua::Value nilValue1 = state["novaluehere"]; 116 | lua::Value nilValue2 = state["novaluehere"]; 117 | lua::Value nilValue3 = state["novaluehere"]; 118 | state.doString("lambda(1,2)"); 119 | assert(intValue == 3); 120 | } 121 | 122 | // Test passing reference to capture 123 | state.set("lambda", [&intValue](int a, int b, int c, int d) { 124 | intValue = a + b + c + d; 125 | }); 126 | state.doString("lambda(4, 8, 12, 14)"); 127 | assert(intValue == 38); 128 | 129 | // Test when we provide more arguments than we need 130 | state.doString("lambda(1,2,3,4,5,6,7,8,9)"); 131 | assert(intValue == 10); 132 | { 133 | lua::Value nilValue1 = state["novaluehere"]; 134 | lua::Value nilValue2 = state["novaluehere"]; 135 | lua::Value nilValue3 = state["novaluehere"]; 136 | state.doString("lambda(1,2,3,4,5,6,7,8,9)"); 137 | assert(intValue == 10); 138 | } 139 | 140 | // Type mismatch exception 141 | // try { 142 | // state["lambda"]("hello"); 143 | // assert(false); 144 | // } catch (lua::TypeMismatchError ex) { 145 | // LUASTATE_DEBUG_LOG("%s", ex.what()); 146 | // LUASTATE_DEBUG_LOG("Exception cought... OK"); 147 | // } 148 | // 149 | // try { 150 | // state.doString("lambda('hello')"); 151 | // assert(false); 152 | // } catch (lua::TypeMismatchError ex) { 153 | // LUASTATE_DEBUG_LOG("%s", ex.what()); 154 | // LUASTATE_DEBUG_LOG("Exception cought... OK"); 155 | // } catch (lua::RuntimeError ex) { 156 | // LUASTATE_DEBUG_LOG("%s", ex.what()); 157 | // LUASTATE_DEBUG_LOG("Exception cought... OK"); 158 | // } 159 | 160 | // Test multi return 161 | state.set("lambda", []() -> std::tuple { 162 | return std::tuple(23, "abc"); 163 | }); 164 | 165 | lua::tie(intValue, cText) = state["lambda"](); 166 | assert(intValue == 23); 167 | assert(strcmp(cText, "abc") == 0); 168 | 169 | // Test class binding 170 | Foo foo(state); 171 | state["Foo_setA"](10); 172 | state["Foo_setB"](20); 173 | assert(foo.a == 10); 174 | assert(foo.b == 20); 175 | 176 | state.set("getFncs", []() 177 | -> std::tuple, std::function, std::function> { 178 | // Error in gcc 4.8.1, we must again specify tuple parameters 179 | return std::make_tuple, std::function, std::function>( 180 | [] () -> int { return 100; }, 181 | [] () -> int { return 200; }, 182 | [] () -> int { return 300; } 183 | ); 184 | }); 185 | int a, b, c; 186 | state.set("setValues", [&a, &b, &c]() 187 | -> std::tuple, std::function, std::function> { 188 | return std::make_tuple( 189 | [&] (int value) { a = value; }, 190 | [&] (int value) { b = value; }, 191 | [&] (int value) { c = value; } 192 | ); 193 | }); 194 | 195 | state.doString("fnc1, fnc2, fnc3 = getFncs()" 196 | "setA, setB, setC = setValues()" 197 | "setA(fnc1()); setB(fnc2()); setC(fnc3())"); 198 | assert(a == 100); 199 | assert(b == 200); 200 | assert(c == 300); 201 | 202 | ////////////////////////////////////////////////////////////////////////////////////////////// 203 | 204 | state.set("goodFnc", [](){ }); 205 | state["goodFnc"](); 206 | state["goodFnc"].call(); 207 | 208 | flag = false; 209 | state.doString("badFnc = function(a,b) local var = a .. b end"); 210 | try { 211 | lua::Value aaa = state["goodFnc"]; 212 | state["badFnc"].call(3); 213 | assert(false); 214 | } catch (lua::RuntimeError ex) { 215 | flag = true; 216 | } 217 | assert(flag == true); 218 | 219 | { 220 | state.doString("passToFunction = { a = 5, nested = { b = 4 } }"); 221 | lua::Value luaValue = state["passToFunction"]; 222 | assert(luaValue["a"] == 5); 223 | 224 | assert(luaValue["nested"]["b"] == 4); 225 | assert(luaValue["a"] == 5); 226 | 227 | auto fnc = [] (const lua::Value& value) { 228 | assert(value["a"] == 5); 229 | assert(value["nested"]["b"] == 4); 230 | assert(value["a"] == 5); 231 | 232 | lua::Value nestedLuaValue = value["nested"]; 233 | assert(nestedLuaValue["b"] == 4); 234 | }; 235 | fnc(luaValue); 236 | fnc(state["passToFunction"]); 237 | 238 | assert(luaValue["a"] == 5); 239 | assert(luaValue["nested"]["b"] == 4); 240 | assert(luaValue["a"] == 5); 241 | 242 | lua::Value nestedLuaValue = luaValue["nested"]; 243 | assert(nestedLuaValue["b"] == 4); 244 | } 245 | 246 | // std::string hello = state["mystr"]; 247 | // hello = state["mystr"]; 248 | // 249 | { // LuaState treats empty return values as nil 250 | lua::Value value; 251 | 252 | value = state.doString("return nil"); 253 | assert(value.is()); 254 | 255 | value = state.doString("return"); 256 | assert(value.is()); 257 | } 258 | 259 | state.checkMemLeaks(); 260 | return 0; 261 | } 262 | -------------------------------------------------------------------------------- /test/main.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // main.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 29/05/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | void runTest(const std::string& filename) 14 | { 15 | printf("#####################################\n"); 16 | printf("## Running test: %s\n", filename.c_str()); 17 | printf("#####################################\n\n"); 18 | 19 | // TODO: search for executables 20 | 21 | #ifdef WIN32 22 | // NOTE: add your own directory according to project 23 | std::string prefix = "Debug\\"; 24 | std::string suffix = ".exe"; 25 | #else 26 | std::string prefix = "./"; 27 | std::string suffix = ""; 28 | #endif 29 | if (system(std::string(prefix + filename + suffix).c_str()) == 0) 30 | printf("Test %s OK...\n\n", filename.c_str()); 31 | else { 32 | printf("Test %s FAILED!\n\n", filename.c_str()); 33 | exit(1); 34 | } 35 | } 36 | 37 | int main(int argc, char** argv) 38 | { 39 | runTest("get_test"); 40 | runTest("lambda_test"); 41 | runTest("ref_test"); 42 | runTest("set_test"); 43 | runTest("state_test"); 44 | runTest("types_test"); 45 | runTest("values_test"); 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /test/ref_test.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // state_tests.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 16/04/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #include "test.h" 10 | 11 | ////////////////////////////////////////////////////////////////////////////////////////////// 12 | int main(int argc, char** argv) 13 | { 14 | lua::State state; 15 | state.doString(createVariables); 16 | 17 | lua::Ref ref = state["table"]["a"]; 18 | lua::Ref tabRef = state["table"]; 19 | 20 | assert(ref.unref() == 'a'); 21 | assert(tabRef.unref()["a"] == 'a'); 22 | 23 | lua::Ref copyRef = ref; 24 | assert(copyRef.unref() == 'a'); 25 | 26 | copyRef = tabRef; 27 | assert(copyRef.unref()["a"] == 'a'); 28 | 29 | state.checkMemLeaks(); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /test/set_test.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // state_tests.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 16/04/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #include "test.h" 10 | 11 | ////////////////////////////////////////////////////////////////////////////////////////////// 12 | int main(int argc, char** argv) 13 | { 14 | // We create state 15 | lua::State state; 16 | 17 | // Set and delete value 18 | state.set("number", 2.5); 19 | state.doString("assert(number == 2.5)"); 20 | state.set("number", nullptr); 21 | state.doString("assert(number == nil)"); 22 | 23 | // Create table with values 24 | state.set("tab", lua::Table()); 25 | state["tab"].set("a", 1); 26 | state["tab"].set("b", 2); 27 | state["tab"].set("c", 3); 28 | state.doString("assert(tab.a == 1)"); 29 | state.doString("assert(tab.b == 2)"); 30 | state.doString("assert(tab.c == 3)"); 31 | state["tab"].set("a", nullptr); 32 | state["tab"].set("b", nullptr); 33 | state["tab"].set("c", nullptr); 34 | state.doString("assert(tab.a == nil)"); 35 | state.doString("assert(tab.b == nil)"); 36 | state.doString("assert(tab.c == nil)"); 37 | 38 | // Set values via lua::Value 39 | { 40 | lua::Value value = state["tab"]; 41 | value.set(1, 1); 42 | value.set(2, 2); 43 | value.set(3, 3); 44 | state.doString("assert(tab[1] == 1)"); 45 | state.doString("assert(tab[2] == 2)"); 46 | state.doString("assert(tab[3] == 3)"); 47 | } 48 | 49 | state.checkMemLeaks(); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /test/state_test.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // state_tests.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 16/04/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #include "test.h" 10 | 11 | #include 12 | 13 | ////////////////////////////////////////////////////////////////////////////////////////////// 14 | int main(int argc, char** argv) 15 | { 16 | lua::State state; 17 | 18 | state.doString("number = 10"); 19 | state.doString("assert(number == 10)"); 20 | 21 | try { 22 | state.doString("we will invoke syntax error"); 23 | assert(false); 24 | } catch (lua::LoadError ex) { 25 | printf("%s\n", ex.what()); 26 | } 27 | 28 | try { 29 | state.doString("nofunction()"); 30 | assert(false); 31 | } catch (lua::RuntimeError ex) { 32 | printf("%s\n", ex.what()); 33 | } 34 | 35 | std::ofstream luaFile; 36 | 37 | try { 38 | state.doFile("no_file_here"); 39 | assert(false); 40 | } catch (lua::LoadError ex) { 41 | printf("%s ", ex.what()); 42 | } 43 | 44 | luaFile.open("test.lua"); 45 | luaFile << "local number = 100; assert(number == 100)" << std::endl; 46 | luaFile.close(); 47 | state.doFile("test.lua"); 48 | 49 | luaFile.open("test.lua"); 50 | luaFile << "nofunction()" << std::endl; 51 | luaFile.close(); 52 | try { 53 | state.doFile("test.lua"); 54 | assert(false); 55 | } catch (lua::RuntimeError ex) { 56 | printf("%s\n", ex.what()); 57 | } 58 | 59 | // Check returning values from doString 60 | int a1, a2, a3; 61 | a1 = state.doString("return 10"); 62 | assert(a1 == 10); 63 | lua::tie(a1) = state.doString("return 100"); 64 | assert(a1 == 100); 65 | lua::tie(a1, a2, a3) = state.doString("return 11, 12, 13"); 66 | assert(a1 == 11 && a2 == 12 && a3 == 13); 67 | lua::tie(a1) = state.doString("return 21, 12, 13"); 68 | assert(a1 == 21); 69 | lua::tie(a1, a2, a3) = state.doString("return 11"); 70 | assert(a1 == 11); 71 | 72 | // Check returning values from doFile 73 | luaFile.open("test.lua"); 74 | luaFile << "return 11, 12, 13" << std::endl; 75 | luaFile.close(); 76 | 77 | a1 = state.doFile("test.lua"); 78 | assert(a1 == 11); 79 | lua::tie(a1, a2, a3) = state.doFile("test.lua"); 80 | assert(a1 == 11 && a2 == 12 && a3 == 13); 81 | 82 | state.checkMemLeaks(); 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /test/test.h: -------------------------------------------------------------------------------- 1 | // 2 | // test.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 16/04/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #define LUASTATE_DEBUG_MODE 10 | #include "../include/LuaState.h" 11 | 12 | #include 13 | 14 | ////////////////////////////////////////////////////////////////////////////////////////////// 15 | static const char* createVariables = R"( 16 | 17 | integer = 10 18 | number = 2.5 19 | char = 'a' 20 | text = "hello" 21 | boolean = true 22 | 23 | table = { 24 | 100, 'hello', true, 25 | a = 'a', b = 'b', c = 'c', 26 | one = 1, two = 2, three = 3, 27 | } 28 | 29 | nested = { ["table"] = table } 30 | nested.nested = nested 31 | 32 | )"; 33 | 34 | ////////////////////////////////////////////////////////////////////////////////////////////// 35 | static const char* createFunctions = R"( 36 | 37 | function getInteger() 38 | return 10 39 | end 40 | 41 | function getTable() 42 | return table 43 | end 44 | 45 | function getNested() 46 | nested.func = getNested 47 | return nested 48 | end 49 | 50 | function getValues() 51 | return 1, 2, 3 52 | end 53 | 54 | function getNestedValues() 55 | return 1, {1, 2, 3}, 3 56 | end 57 | 58 | function pack(...) 59 | return {...} 60 | end 61 | 62 | )"; 63 | 64 | -------------------------------------------------------------------------------- /test/types_test.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // state_tests.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 16/04/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #include "test.h" 10 | 11 | ////////////////////////////////////////////////////////////////////////////////////////////// 12 | int main(int argc, char** argv) 13 | { 14 | // We create state and variables 15 | lua::State state; 16 | state.doString(createVariables); 17 | 18 | // Boolean 19 | bool boolValue = false; 20 | 21 | assert(state["boolean"] == true); 22 | assert((boolValue = state["boolean"]) == true); 23 | 24 | // All numeric types 25 | int intValue; 26 | long longValue; 27 | long long longlongValue; 28 | unsigned unsignedValue; 29 | long unsigned unsignedLongValue; 30 | long long unsigned unsignedLongLongValue; 31 | short shortValue; 32 | unsigned short unsignedShortValue; 33 | 34 | state.set("value", 1); 35 | assert(state["value"] == 1); 36 | state.set("value", 1L); 37 | assert(state["value"] == 1); 38 | state.set("value", 1LL); 39 | assert(state["value"] == 1); 40 | state.set("value", 1U); 41 | assert(state["value"] == 1); 42 | state.set("value", 1LU); 43 | assert(state["value"] == 1); 44 | state.set("value", 1LLU); 45 | assert(state["value"] == 1); 46 | state.set("value", static_cast(1)); 47 | assert(state["value"] == 1); 48 | state.set("value", static_cast(1)); 49 | assert(state["value"] == 1); 50 | 51 | assert(state["integer"] == 10); 52 | assert(state["integer"] != 5); 53 | assert(state["integer"] > 9); 54 | assert(state["integer"] < 11); 55 | assert(state["integer"] >= 10); 56 | assert(state["integer"] <= 10); 57 | 58 | assert(state["integer"] == 10L); 59 | assert(state["integer"] != 5L); 60 | assert(state["integer"] > 9L); 61 | assert(state["integer"] < 11L); 62 | assert(state["integer"] >= 10L); 63 | assert(state["integer"] <= 10L); 64 | 65 | assert(state["integer"] == 10LL); 66 | assert(state["integer"] != 5LL); 67 | assert(state["integer"] > 9LL); 68 | assert(state["integer"] < 11LL); 69 | assert(state["integer"] >= 10LL); 70 | assert(state["integer"] <= 10LL); 71 | 72 | assert(state["integer"] == 10U); 73 | assert(state["integer"] != 5U); 74 | assert(state["integer"] > 9U); 75 | assert(state["integer"] < 11U); 76 | assert(state["integer"] >= 10U); 77 | assert(state["integer"] <= 10U); 78 | 79 | assert(state["integer"] == 10UL); 80 | assert(state["integer"] != 5UL); 81 | assert(state["integer"] > 9UL); 82 | assert(state["integer"] < 11UL); 83 | assert(state["integer"] >= 10UL); 84 | assert(state["integer"] <= 10UL); 85 | 86 | assert(state["integer"] == 10ULL); 87 | assert(state["integer"] != 5ULL); 88 | assert(state["integer"] > 9ULL); 89 | assert(state["integer"] < 11ULL); 90 | assert(state["integer"] >= 10ULL); 91 | assert(state["integer"] <= 10ULL); 92 | 93 | assert(state["integer"] == static_cast(10)); 94 | assert(state["integer"] != static_cast(5)); 95 | assert(state["integer"] > static_cast(9)); 96 | assert(state["integer"] < static_cast(11)); 97 | assert(state["integer"] >= static_cast(10)); 98 | assert(state["integer"] <= static_cast(10)); 99 | 100 | assert(state["integer"] == static_cast(10)); 101 | assert(state["integer"] != static_cast(5)); 102 | assert(state["integer"] > static_cast(9)); 103 | assert(state["integer"] < static_cast(11)); 104 | assert(state["integer"] >= static_cast(10)); 105 | assert(state["integer"] <= static_cast(10)); 106 | 107 | 108 | assert((intValue = state["integer"]) == 10); 109 | assert((intValue = state["integer"]) != 5); 110 | assert((intValue = state["integer"]) > 9); 111 | assert((intValue = state["integer"]) < 11); 112 | assert((intValue = state["integer"]) >= 10); 113 | assert((intValue = state["integer"]) <= 10); 114 | 115 | assert((longValue = state["integer"]) == 10L); 116 | assert((longValue = state["integer"]) != 5L); 117 | assert((longValue = state["integer"]) > 9L); 118 | assert((longValue = state["integer"]) < 11L); 119 | assert((longValue = state["integer"]) >= 10L); 120 | assert((longValue = state["integer"]) <= 10L); 121 | 122 | assert((longlongValue = state["integer"]) == 10LL); 123 | assert((longlongValue = state["integer"]) != 5LL); 124 | assert((longlongValue = state["integer"]) > 9LL); 125 | assert((longlongValue = state["integer"]) < 11LL); 126 | assert((longlongValue = state["integer"]) >= 10LL); 127 | assert((longlongValue = state["integer"]) <= 10LL); 128 | 129 | assert((unsignedValue = state["integer"]) == 10U); 130 | assert((unsignedValue = state["integer"]) != 5U); 131 | assert((unsignedValue = state["integer"]) > 9U); 132 | assert((unsignedValue = state["integer"]) < 11U); 133 | assert((unsignedValue = state["integer"]) >= 10U); 134 | assert((unsignedValue = state["integer"]) <= 10U); 135 | 136 | assert((unsignedLongValue = state["integer"]) == 10UL); 137 | assert((unsignedLongValue = state["integer"]) != 5UL); 138 | assert((unsignedLongValue = state["integer"]) > 9UL); 139 | assert((unsignedLongValue = state["integer"]) < 11UL); 140 | assert((unsignedLongValue = state["integer"]) >= 10UL); 141 | assert((unsignedLongValue = state["integer"]) <= 10UL); 142 | 143 | assert((unsignedLongLongValue = state["integer"]) == 10ULL); 144 | assert((unsignedLongLongValue = state["integer"]) != 5ULL); 145 | assert((unsignedLongLongValue = state["integer"]) > 9ULL); 146 | assert((unsignedLongLongValue = state["integer"]) < 11ULL); 147 | assert((unsignedLongLongValue = state["integer"]) >= 10ULL); 148 | assert((unsignedLongLongValue = state["integer"]) <= 10ULL); 149 | 150 | assert((shortValue = state["integer"]) == 10); 151 | assert((shortValue = state["integer"]) != 5); 152 | assert((shortValue = state["integer"]) > 9); 153 | assert((shortValue = state["integer"]) < 11); 154 | assert((shortValue = state["integer"]) >= 10); 155 | assert((shortValue = state["integer"]) <= 10); 156 | 157 | assert((unsignedShortValue = state["integer"]) == 10); 158 | assert((unsignedShortValue = state["integer"]) != 5); 159 | assert((unsignedShortValue = state["integer"]) > 9); 160 | assert((unsignedShortValue = state["integer"]) < 11); 161 | assert((unsignedShortValue = state["integer"]) >= 10); 162 | assert((unsignedShortValue = state["integer"]) <= 10); 163 | 164 | // All floating types 165 | float floatValue; 166 | double doubleValue; 167 | long double longDoubleValue; 168 | 169 | state.set("value", 1.0); 170 | assert(state["value"] == 1); 171 | state.set("value", 1.f); 172 | assert(state["value"] == 1); 173 | state.set("value", 1.l); 174 | assert(state["value"] == 1); 175 | 176 | assert(state["number"] == 2.5); 177 | assert(state["number"] != 3.5); 178 | assert(state["number"] > 2.0); 179 | assert(state["number"] < 3.0); 180 | assert(state["number"] >= 2.5); 181 | assert(state["number"] <= 3.5); 182 | 183 | assert(state["number"] == 2.5f); 184 | assert(state["number"] != 3.5f); 185 | assert(state["number"] > 2.f); 186 | assert(state["number"] < 3.f); 187 | assert(state["number"] >= 2.5f); 188 | assert(state["number"] <= 3.5f); 189 | 190 | assert(state["number"] == 2.5l); 191 | assert(state["number"] != 3.5l); 192 | assert(state["number"] > 2.l); 193 | assert(state["number"] < 3.l); 194 | assert(state["number"] >= 2.5l); 195 | assert(state["number"] <= 3.5l); 196 | 197 | 198 | assert((doubleValue = state["number"]) == 2.5); 199 | assert((doubleValue = state["number"]) != 3.5); 200 | assert((doubleValue = state["number"]) > 2.0); 201 | assert((doubleValue = state["number"]) < 3.0); 202 | assert((doubleValue = state["number"]) >= 2.5); 203 | assert((doubleValue = state["number"]) <= 3.5); 204 | 205 | assert((floatValue = state["number"]) == 2.5f); 206 | assert((floatValue = state["number"]) != 3.5f); 207 | assert((floatValue = state["number"]) > 2.f); 208 | assert((floatValue = state["number"]) < 3.f); 209 | assert((floatValue = state["number"]) >= 2.5f); 210 | assert((floatValue = state["number"]) <= 3.5f); 211 | 212 | assert((longDoubleValue = state["number"]) == 2.5l); 213 | assert((longDoubleValue = state["number"]) != 3.5l); 214 | assert((longDoubleValue = state["number"]) > 2.l); 215 | assert((longDoubleValue = state["number"]) < 3.l); 216 | assert((longDoubleValue = state["number"]) >= 2.5l); 217 | assert((longDoubleValue = state["number"]) <= 3.5l); 218 | 219 | // All character types 220 | char charValue; 221 | // signed char signedCharValue; 222 | unsigned char unsignedCharValue; 223 | // wchar_t wcharValue; 224 | // char16_t char16Value; 225 | // char32_t char32Value; 226 | 227 | const char* charString; 228 | // const signed char* signedCharString; 229 | const unsigned char* unsignedCharString; 230 | // const wchar_t* wcharString; 231 | // const char16_t* char16String; 232 | // const char32_t* char32String; 233 | 234 | state.set("value", 'x'); 235 | assert(state["value"] == 'x'); 236 | state.set("value", "ahoj"); 237 | assert(strcmp(state["value"], "ahoj") == 0); 238 | 239 | assert(state["char"] == 'a'); 240 | assert(state["char"] != 'b'); 241 | assert((charValue = state["char"]) == 'a'); 242 | assert((charValue = state["char"]) != 'b'); 243 | 244 | unsignedCharValue = 'a'; 245 | assert(state["char"] == unsignedCharValue); 246 | unsignedCharValue = 'b'; 247 | assert(state["char"] != 'b'); 248 | assert((unsignedCharValue = state["char"]) == 'a'); 249 | assert((unsignedCharValue = state["char"]) != 'b'); 250 | 251 | assert(strcmp(state["text"], "hello") == 0); 252 | assert(strcmp(state["text"], "bannana") != 0); 253 | assert(strcmp(charString = state["text"], "hello") == 0); 254 | assert(strcmp(charString = state["text"], "bannana") != 0); 255 | 256 | unsignedCharString = state["text"]; 257 | assert(unsignedCharString[0] == 'h'); 258 | assert(unsignedCharString[1] == 'e'); 259 | assert(unsignedCharString[2] == 'l'); 260 | assert(unsignedCharString[3] == 'l'); 261 | assert(unsignedCharString[4] == 'o'); 262 | assert(unsignedCharString[5] == '\0'); 263 | 264 | std::string stringValue = "test string"; 265 | state.set("value", stringValue); 266 | assert(state["value"] == stringValue); 267 | assert((stringValue = state["text"].toString()) == "hello"); 268 | assert((stringValue = state["text"].toString()) != "bannana"); 269 | 270 | char binaryData[3]; 271 | binaryData[0] = 'a'; 272 | binaryData[1] = 'b'; 273 | binaryData[2] = 'c'; 274 | state.setData("binary", binaryData, 3); 275 | assert(strcmp(state["binary"], "abc") == 0); 276 | 277 | state.checkMemLeaks(); 278 | return 0; 279 | } 280 | -------------------------------------------------------------------------------- /test/values_test.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // state_tests.h 3 | // LuaState 4 | // 5 | // Created by Simon Mikuda on 16/04/14. 6 | // 7 | // See LICENSE and README.md files 8 | 9 | #include "test.h" 10 | 11 | ////////////////////////////////////////////////////////////////////////////////////////////// 12 | int main(int argc, char** argv) 13 | { 14 | lua::State state; 15 | state.doString(createVariables); 16 | state.doString(createFunctions); 17 | 18 | { 19 | // Test move sematics with lvalue 20 | assert(state["number"] == 2.5); 21 | assert(state["getValues"]() == 1); 22 | 23 | // Test copy sematics with rvalue 24 | lua::Value function = state["getInteger"]; 25 | lua::Value value = state["number"]; 26 | assert(function() == 10); 27 | assert(value == 2.5); 28 | assert(function() == 10); 29 | assert(value == 2.5); 30 | assert(function() == 10); 31 | assert(value == 2.5); 32 | 33 | value = state["number"]; 34 | value = state["number"]; 35 | value = state["number"]; 36 | assert(function() == 10); 37 | assert(value == 2.5); 38 | assert(function() == 10); 39 | assert(value == 2.5); 40 | assert(function() == 10); 41 | assert(value == 2.5); 42 | 43 | value = state["getInteger"]; 44 | function = state["number"]; 45 | function = state["getInteger"]; 46 | value = state["number"]; 47 | assert(function() == 10); 48 | assert(value == 2.5); 49 | assert(function() == 10); 50 | assert(value == 2.5); 51 | assert(function() == 10); 52 | assert(value == 2.5); 53 | 54 | value = function; 55 | value = function; 56 | value = function; 57 | function = state["number"]; 58 | assert(function == 2.5); 59 | assert(value() == 10); 60 | assert(function == 2.5); 61 | assert(value() == 10); 62 | assert(function == 2.5); 63 | assert(value() == 10); 64 | } 65 | 66 | // Test deletion in FILO order 67 | { 68 | lua::Value v1 = state["table"]["a"]; 69 | { 70 | lua::Value v2 = state["table"]["b"]; 71 | assert(v2 == 'b'); 72 | assert(v1 == 'a'); 73 | { 74 | lua::Value v3 = state["table"]["c"]; 75 | assert(v1 == 'a'); 76 | assert(v2 == 'b'); 77 | assert(v3 == 'c'); 78 | } 79 | assert(v2 == 'b'); 80 | assert(v1 == 'a'); 81 | } 82 | assert(v1 == 'a'); 83 | } 84 | 85 | // Test deletion FIFO order 86 | lua::Value* v1 = new lua::Value(state["table"]["a"]); 87 | lua::Value* v2 = new lua::Value(state["table"]["b"]); 88 | lua::Value* v3 = new lua::Value(state["table"]["c"]); 89 | lua::Value* v4 = new lua::Value(state["table"]["one"]); 90 | lua::Value* v5 = new lua::Value(state["table"]["two"]); 91 | lua::Value* v6 = new lua::Value(state["table"]["three"]); 92 | 93 | assert(*v1 == 'a'); 94 | assert(*v2 == 'b'); 95 | assert(*v3 == 'c'); 96 | assert(*v4 == 1); 97 | assert(*v5 == 2); 98 | assert(*v6 == 3); 99 | delete v1; 100 | 101 | assert(*v2 == 'b'); 102 | assert(*v3 == 'c'); 103 | assert(*v4 == 1); 104 | assert(*v5 == 2); 105 | assert(*v6 == 3); 106 | delete v2; 107 | 108 | assert(*v3 == 'c'); 109 | assert(*v4 == 1); 110 | assert(*v5 == 2); 111 | assert(*v6 == 3); 112 | delete v3; 113 | 114 | assert(*v4 == 1); 115 | assert(*v5 == 2); 116 | assert(*v6 == 3); 117 | delete v4; 118 | 119 | assert(*v5 == 2); 120 | assert(*v6 == 3); 121 | delete v5; 122 | 123 | assert(*v6 == 3); 124 | delete v6; 125 | 126 | // Test deletion in random order 127 | v1 = new lua::Value(state["table"]["a"]); 128 | v2 = new lua::Value(state["table"]["b"]); 129 | v3 = new lua::Value(state["table"]["c"]); 130 | v4 = new lua::Value(state["table"]["one"]); 131 | v5 = new lua::Value(state["table"]["two"]); 132 | v6 = new lua::Value(state["table"]["three"]); 133 | 134 | assert(*v1 == 'a'); 135 | assert(*v2 == 'b'); 136 | assert(*v3 == 'c'); 137 | assert(*v4 == 1); 138 | assert(*v5 == 2); 139 | assert(*v6 == 3); 140 | delete v6; 141 | 142 | assert(*v1 == 'a'); 143 | assert(*v2 == 'b'); 144 | assert(*v3 == 'c'); 145 | assert(*v4 == 1); 146 | assert(*v5 == 2); 147 | delete v3; 148 | 149 | assert(*v1 == 'a'); 150 | assert(*v2 == 'b'); 151 | assert(*v4 == 1); 152 | assert(*v5 == 2); 153 | delete v1; 154 | 155 | assert(*v2 == 'b'); 156 | assert(*v4 == 1); 157 | assert(*v5 == 2); 158 | delete v5; 159 | 160 | assert(*v2 == 'b'); 161 | assert(*v4 == 1); 162 | delete v4; 163 | 164 | assert(*v2 == 'b'); 165 | delete v2; 166 | 167 | // Test copying values 168 | v1 = new lua::Value(state["table"]["a"]); 169 | v2 = new lua::Value(*v1); 170 | v3 = new lua::Value(*v2); 171 | 172 | assert(*v1 == 'a'); 173 | assert(*v2 == 'a'); 174 | assert(*v3 == 'a'); 175 | delete v1; 176 | 177 | assert(*v2 == 'a'); 178 | assert(*v3 == 'a'); 179 | delete v2; 180 | 181 | assert(*v3 == 'a'); 182 | delete v3; 183 | 184 | // Test moving and copying values to functions 185 | { 186 | auto constCopyValueFnc = [](const lua::Value& value){ assert(value == 3); }; 187 | auto copyValueFnc = [](const lua::Value& value){ assert(value == 3); }; 188 | auto moveValueFnc = []( lua::Value&& value){ assert(value == 3); }; 189 | 190 | constCopyValueFnc(state["table"]["three"]); 191 | copyValueFnc(state["table"]["three"]); 192 | moveValueFnc(state["table"]["three"]); 193 | 194 | lua::Value value = state["table"]["three"]; 195 | constCopyValueFnc(value); 196 | copyValueFnc(value); 197 | moveValueFnc(state["table"]["three"]); 198 | } 199 | 200 | // Test geting value from Lua and sending value back to Lua 201 | state.doString("function moveValues(tab) assert(tab.a == 'a') assert(tab.b == 'b') assert(tab.c == 'c') assert(tab.one == 1) assert(tab.two == 2) assert(tab.three == 3) end"); 202 | 203 | state.doString("moveValues(table)"); 204 | 205 | state["moveValues"](state["table"]); 206 | state["moveValues"](state["table"], state["table"]); 207 | 208 | v1 = new lua::Value(state["table"]); 209 | state["moveValues"](*v1); 210 | state["moveValues"](*v1); 211 | delete v1; 212 | 213 | state.checkMemLeaks(); 214 | return 0; 215 | } 216 | --------------------------------------------------------------------------------