### Minimal LuaCpp Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/README.md Demonstrates the basic setup for creating a Lua context, compiling a Lua string, and running it. ```cpp #include #include int main() { // Create context LuaCpp::LuaContext ctx; // Compile Lua code ctx.CompileString("hello", "print('Hello from Lua!')"); // Execute ctx.Run("hello"); return 0; } ``` -------------------------------- ### LuaCpp Hello World Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/1-introduction.md A basic example demonstrating how to initialize LuaCpp and run a simple Lua print statement from C++. ```c++ #include #include using namespace LuaCpp; using namespace LuaCpp::Registry; using namespace LuaCpp::Engine; int main(int argc, char **argv) { std::cout << "Hi from C++, this is a demo how LuaCpp can be used" << "\n"; LuaContext lua; // The simples way is to use CompileStringAndRun method try { lua.CompileStringAndRun("print('The fastest way to start using lua in a project')"); } catch (std::runtime_error& e) { std::cout << e.what() << '\n'; } } ``` -------------------------------- ### Compiling and Running LuaCpp Hello World Source: https://github.com/jordanvrtanoski/luacpp/blob/main/README.md Provides the command-line instructions to compile the C++ 'Hello World' example using GCC and then execute the compiled program. Ensure LuaCpp and Lua libraries are installed and accessible. ```bash ~$ gcc hello.cpp -I /usr/local/include/LuaCpp -I /usr/include/lua5.3/ -lluacpp -llua5.3 -lstdc++ -o hello ~$ hello ``` -------------------------------- ### Install LuaCpp Project Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/1-introduction.md Clone the project and build it from the root directory using CMake and Make. ```bash mkdir build cd build cmake ../Source make -j 4 make install ``` -------------------------------- ### LuaCpp Hello World Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/README.md Demonstrates the simplest way to integrate and run Lua code within a C++ application using LuaCpp's CompileStringAndRun method. This example shows basic output from both C++ and Lua. ```c++ #include #include using namespace LuaCpp; using namespace LuaCpp::Registry; using namespace LuaCpp::Engine; int main(int argc, char **argv) { std::cout << "Hi from C++, this is a demo how LuaCpp can be used" << "\n"; LuaContext lua; // The simples way is to use CompileStringAndRun method try { lua.CompileStringAndRun("print('The fastest way to start using lua in a project')"); } catch (std::runtime_error& e) { std::cout << e.what() << '\n'; } } ``` -------------------------------- ### LuaState Lifecycle Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/04-luastate.md Demonstrates the creation and automatic cleanup of LuaState instances using a LuaContext. ```cpp #include #include using namespace LuaCpp; using namespace LuaCpp::Engine; int main() { // Create a context LuaContext ctx; ctx.CompileString("demo", "x = 10"); // Method 1: Using newState { auto state = ctx.newState(); // Takes ownership lua_pushstring(*state, "hello"); state->PrintStack(std::cout); } // state is automatically closed here // Method 2: With custom allocator StateParams params; params.allocator = nullptr; // use default auto state2 = ctx.newState(params); return 0; } ``` -------------------------------- ### Compile and Run LuaCpp Demo Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/README.md Shows the compilation and execution commands for the minimal LuaCpp example. ```bash g++ -I/usr/local/include/LuaCpp -I/usr/include/lua5.3 \ -lluacpp -llua5.3 -std=c++17 -o demo demo.cpp ./demo # Output: Hello from Lua! ``` -------------------------------- ### Build PDF Documentation Source: https://github.com/jordanvrtanoski/luacpp/blob/main/README.md Install necessary LaTeX packages and Graphviz. Then, use CMake and Make to build the PDF documentation. ```bash sudo apt-get install texlive-latex-base texlive-latex-recommended texlive-latex-extra graphviz mkdir build cd build cmake ../Source make doc_pdf ``` -------------------------------- ### Basic StatePool Usage Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/06-statepool.md Demonstrates how to get a StatePool, acquire a Lua state, use it, and then release it back to the pool. ```cpp LuaContext ctx; ctx.CompileString("task", "return x * 2"); // Get pool and acquire state StatePool& pool = ctx.getPool("default"); auto state = pool.acquire(); // Use state... pool.release(std::move(state)); ``` -------------------------------- ### Install Google Test Library Source: https://github.com/jordanvrtanoski/luacpp/blob/main/Source/CMakeLists.txt This snippet shows how to download and build the Google Test framework as a standalone library using CMake's ExternalProject module. It specifies the Git repository, tag, and installation prefix. ```cmake set(GOOGLETEST_INSTALL "${CMAKE_CURRENT_BINARY_DIR}/googletest-install") set(GOOGLETEST_INCLUDE "${GOOGLETEST_INSTALL}/include") include(ExternalProject) ExternalProject_Add(googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG v1.14.0 SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-src" BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-build" CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${GOOGLETEST_INSTALL} -DINCLUDE_INSTALL_DIR=${GOOGLETEST_INSTALL} TEST_COMMAND "" ) ``` -------------------------------- ### Run Coverage Tests Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/1-introduction.md Install gcovr, configure the build for Coverage, and generate CLI and HTML coverage reports. ```bash apt install gcovr mkdir build cd build cmake -DCMAKE_BUILD_TYPE=Coverage ../Source make -j 4 make coverage-cli make coverage-html ``` -------------------------------- ### Install C++ Module Library Source: https://github.com/jordanvrtanoski/luacpp/blob/main/Source/CMakeLists.txt Installs the C++ module library, including its header files, to the appropriate locations. ```cmake install(TARGETS luacpp_module EXPORT LuaCppTargets LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} FILE_SET CXX_MODULES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME} ) ``` -------------------------------- ### Install LuaCpp Library and Headers Source: https://github.com/jordanvrtanoski/luacpp/blob/main/Source/CMakeLists.txt Installs the LuaCpp library targets and header files to their designated locations. Configures and installs package configuration files for CMake. ```cmake include(CMakePackageConfigHelpers) set(CMAKE_CONFIG_DEST "${CMAKE_INSTALL_LIBDIR}/${PROJECT_NAME}/cmake") set(LuaCpp_INCLUDE_DIR "${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}") set(LuaCpp_INSTALL_LIBDIR "${CMAKE_INSTALL_LIBDIR}") install(TARGETS luacpp LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) install(TARGETS luacpp_static DESTINATION ${CMAKE_INSTALL_LIBDIR}) install(FILES LuaCpp.hpp Lua.hpp LuaContext.hpp LuaMetaObject.hpp LuaVersion.hpp DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}") install(DIRECTORY ${CMAKE_SOURCE_DIR}/Registry ${CMAKE_SOURCE_DIR}/Engine DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}" FILES_MATCHING PATTERN "*.hpp" ) configure_package_config_file( LuaCppConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/LuaCppConfig.cmake INSTALL_DESTINATION "${CMAKE_CONFIG_DEST}" PATH_VARS LuaCpp_INCLUDE_DIR LuaCpp_INSTALL_LIBDIR ) write_basic_package_version_file( ${CMAKE_CURRENT_BINARY_DIR}/LuaCppConfigVersion.cmake VERSION 0.1.0 COMPATIBILITY SameMajorVersion ARCH_INDEPENDENT ) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/LuaCppConfigVersion.cmake ${CMAKE_CURRENT_BINARY_DIR}/LuaCppConfig.cmake DESTINATION ${CMAKE_CONFIG_DEST} ) ``` -------------------------------- ### Initialize LuaRegistry Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/07-registry.md Initializes an empty LuaRegistry. No setup is required before calling this constructor. ```cpp LuaRegistry registry; ``` -------------------------------- ### Build LuaCpp Documentation Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/10-version-and-utilities.md Generates PDF documentation for LuaCpp. Requires LaTeX and Graphviz to be installed. ```bash cmake ../Source make doc_pdf ``` -------------------------------- ### Example: Acquire and Release Lua State Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/06-statepool.md Demonstrates the typical usage pattern of acquiring a Lua state, using it, and then releasing it back to the pool. ```cpp auto state = pool.acquire(); // Use state... pool.release(std::move(state)); ``` -------------------------------- ### LuaTTable Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/02-types.md Demonstrates creating a LuaTTable, setting values with different key types (integer and string), and adding it as a global variable to a Lua context. ```cpp auto tbl = std::make_shared(); tbl->setValue(Table::Key(1), std::make_shared("first")); tbl->setValue(Table::Key("name"), std::make_shared("Alice")); ctx.AddGlobalVariable("config", tbl); ``` -------------------------------- ### Complete Pool Configuration Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/06-statepool.md Demonstrates chaining multiple builder methods to create a comprehensive PoolConfig. This sets libraries, a global variable, maximum pool size, and an exhaustion timeout. ```cpp using namespace LuaCpp::Engine; PoolConfig config; config .SetLibraries({"math", "string"}) .AddGlobalVariable("timeout", std::make_shared(30)) .SetMaxSize(10) .SetExhaustionTimeoutMs(5000); ``` -------------------------------- ### Minimal LuaCpp Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/09-api-summary.md Demonstrates the basic usage of LuaCpp by creating a context, adding a global variable, compiling a Lua script, and running it. ```cpp #include #include using namespace LuaCpp; using namespace LuaCpp::Engine; int main() { // Create context LuaContext ctx; // Add a global variable ctx.AddGlobalVariable("answer", std::make_shared(42)); // Compile and run code ctx.CompileString("demo", "print('The answer is', answer)"); ctx.Run("demo"); return 0; } ``` -------------------------------- ### Execute Uploaded Lua Code Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/07-registry.md Example demonstrating how to compile, upload, and execute Lua code using LuaCodeSnippet. ```cpp auto snippet = compiler.CompileString("demo", "print('hello')"); auto state = ctx.newState(); snippet->UploadCode(*state); lua_call(*state, 0, 0); // Execute ``` -------------------------------- ### Compile and Run C++ Demo Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/09-api-summary.md Shows the compilation command and execution for the minimal C++ LuaCpp example, including the expected output. ```bash g++ -I/usr/local/include/LuaCpp -I/usr/include/lua5.3 \ -lluacpp -llua5.3 -lstdc++ -o demo demo.cpp ./demo # Output: The answer is 42 ``` -------------------------------- ### Complete Lua C++ Integration Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/03-lualibrary.md Demonstrates setting up a Lua context, defining C++ functions (sum, multiply), adding them to a Lua library, and executing Lua scripts that call these functions. Includes error handling for script execution. ```cpp #include #include using namespace LuaCpp; using namespace LuaCpp::Registry; using namespace LuaCpp::Engine; extern "C" { static int sum(lua_State *L) { int n = lua_gettop(L); lua_Number total = 0.0; for (int i = 1; i <= n; i++) { if (!lua_isnumber(L, i)) { lua_pushliteral(L, "argument must be a number"); lua_error(L); } total += lua_tonumber(L, i); } lua_pushnumber(L, total); return 1; } static int multiply(lua_State *L) { double a = luaL_checknumber(L, 1); double b = luaL_checknumber(L, 2); lua_pushnumber(L, a * b); return 1; } } int main() { LuaContext ctx; auto mathlib = std::make_shared("mathext"); mathlib->AddCFunction("sum", sum); mathlib->AddCFunction("multiply", multiply); ctx.AddLibrary(mathlib); try { ctx.CompileStringAndRun(R"( print("Result:", mathext.sum(1, 2, 3, 4)) print("Product:", mathext.multiply(5, 6)) )"); } catch (const std::runtime_error &e) { std::cout << "Error: " << e.what() << std::endl; } return 0; } ``` -------------------------------- ### LuaTNumber Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/02-types.md Demonstrates creating a LuaTNumber object, initializing it with a double value, and adding it as a global variable to a Lua context. ```cpp auto num = std::make_shared(3.14159); ctx.AddGlobalVariable("pi", num); ``` -------------------------------- ### Adding Custom C Library to Lua Engine Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/1-introduction.md This C++ example shows how to register a custom C function as a library in the LuaContext. The example includes a C function to sum numerical arguments and demonstrates how to add it to a LuaLibrary and then to the LuaContext. ```c++ #include #include #include using namespace LuaCpp; using namespace LuaCpp::Registry; using namespace LuaCpp::Engine; extern "C" { static int _sum (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ lua_Number sum = 0.0; int i; for (i = 1; i <= n; i++) { if (!lua_isnumber(L, i)) { lua_pushliteral(L, "incorrect argument"); lua_error(L); } sum += lua_tonumber(L, i); } lua_pushnumber(L, sum); /* second result */ return 1; /* number of results */ } } int main(int argc, char **argv) { // Creage Lua context LuaContext lua; // Create library "foo" conatining the "foo" function std::shared_ptr lib = std::make_shared("foolib"); lib->AddCFunction("sum", _sum); // Add library to the context lua.AddLibrary(lib); // Run the context try { lua.CompileStringAndRun("print(\"Result of calling foolib.sum(1,2,3,4) = \" .. foolib.sum(1,2,3,4))"); } catch (std::runtime_error& e) { std::cout << e.what() << '\n'; } } ``` -------------------------------- ### Example: Manual Release of PooledState Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/06-statepool.md Illustrates acquiring a pooled state, performing operations, and then manually releasing it back to the pool before its scope ends. ```cpp { auto pooled = ctx.AcquirePooledStateRAII(); // Use pooled state... pooled.release(); // Return early // Destructor now does nothing } ``` -------------------------------- ### LuaTBoolean Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/02-types.md Demonstrates creating a LuaTBoolean object, initializing it with a boolean value, and adding it as a global variable to a Lua context. ```cpp auto flag = std::make_shared(true); ctx.AddGlobalVariable("enabled", flag); ``` -------------------------------- ### Access Standard Lua Libraries Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/10-version-and-utilities.md Examples of how to use common standard Lua libraries like math, string, and table within Lua scripts. ```lua math.sqrt(16) string.upper("hello") table.insert(myTable, value) ``` -------------------------------- ### Complete Example: Wrapping a C++ Map with LuaCpp Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/08-metaobjects.md This example demonstrates how to wrap a C++ `std::map` within a custom `LuaMetaObject` subclass (`LuaConfigMap`) and expose it to Lua. It shows how to add, access, and modify map elements from both C++ and Lua. ```cpp #include #include #include using namespace LuaCpp; using namespace LuaCpp::Engine; // C++ class to wrap class ConfigMap { public: std::map data; ConfigMap() : data() {} }; // LuaMetaObject subclass class LuaConfigMap : public LuaMetaObject { private: ConfigMap *cfg; public: LuaConfigMap() : LuaMetaObject(), cfg(nullptr) { cfg = new ConfigMap(); } ~LuaConfigMap() { delete cfg; } ConfigMap *getConfig() { return cfg; } std::shared_ptr getValue(std::string &key) override { if (cfg->data.count(key)) { return std::make_shared(cfg->data[key]); } return std::make_shared(); } void setValue(std::string &key, std::shared_ptr val) override { if (auto num = std::dynamic_pointer_cast(val)) { cfg->data[key] = num->getValue(); } } }; int main() { LuaContext ctx; // Create wrapped object auto wrapped = std::make_shared(); wrapped->getConfig()->data["timeout"] = 30.0; wrapped->getConfig()->data["retries"] = 3.0; // Add to Lua context ctx.AddGlobalVariable("config", wrapped); // Access from Lua ctx.CompileStringAndRun(R"( print("Timeout:", config.timeout) print("Retries:", config.retries) config.timeout = 60 config.newSetting = 42 )"); // Check modifications in C++ std::cout << "Config timeout: " << wrapped->getConfig()->data["timeout"] << std::endl; std::cout << "Config newSetting: " << wrapped->getConfig()->data["newSetting"] << std::endl; return 0; } ``` -------------------------------- ### LuaTNil Usage Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/02-types.md Demonstrates how to create and use a `LuaTNil` object, setting it as a global variable in the Lua context. ```cpp auto nil = std::make_shared(); ctx.AddGlobalVariable("empty", nil); ``` -------------------------------- ### LuaState PrintStack Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/04-luastate.md Illustrates how to print the current contents of the Lua stack to an output stream for debugging purposes. ```cpp auto state = ctx.newState(); lua_pushstring(*state, "test"); lua_pushnumber(*state, 42); state->PrintStack(std::cout); // Output: Stack (top=2): [1]=string: "test", [2]=number: 42 ``` -------------------------------- ### Run Coverage Test Source: https://github.com/jordanvrtanoski/luacpp/blob/main/README.md Install gcovr. Configure the build with Coverage type using CMake, then build and run the coverage tests. ```bash apt install gcovr mkdir build cd build cmake -DCMAKE_BUILD_TYPE=Coverage ../Source make -j$(nproc) make coverage-cli make coverage-html ``` -------------------------------- ### Example: Using Arrow Operator on PooledState Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/06-statepool.md Shows how to acquire a pooled state and call a method on the underlying LuaState using the arrow operator for convenience. ```cpp auto pooled = ctx.AcquirePooledStateRAII(); pooled->PrintStack(std::cout); ``` -------------------------------- ### Complete Lua C++ Example with Script Caching Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/07-registry.md Demonstrates compiling and caching multiple Lua scripts using LuaCpp. It shows how to execute cached scripts repeatedly for performance gains. ```cpp #include #include using namespace LuaCpp; using namespace LuaCpp::Registry; int main() { LuaContext ctx; // Compile and cache multiple scripts ctx.CompileString("add", "return a + b"); ctx.CompileString("greet", "print('Hello, ' .. name)"); // Execute script 1 many times for (int i = 0; i < 100; i++) { LuaEnvironment env; env["a"] = std::make_shared(i); env["b"] = std::make_shared(100); ctx.RunWithEnvironment("add", env); } // Execute script 2 many times for (int i = 0; i < 50; i++) { LuaEnvironment env; env["name"] = std::make_shared("User"); ctx.RunWithEnvironment("greet", env); } return 0; } ``` -------------------------------- ### Example: Using Dereference Operator on PooledState Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/06-statepool.md Demonstrates acquiring a pooled state using RAII and then calling a method on the underlying LuaState via the dereference operator. ```cpp auto pooled = ctx.AcquirePooledStateRAII(); (*pooled).PrintStack(std::cout); ``` -------------------------------- ### LuaState State Sharing Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/04-luastate.md Shows how to wrap an existing Lua state without taking ownership, preventing the wrapper's destructor from closing it. ```cpp lua_State *rawL = lua_newstate(...); { LuaState shared(rawL, true); // Does not own rawL // Use shared... } // rawL not closed; caller responsible lua_close(rawL); ``` -------------------------------- ### LuaTString Usage Example Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/02-types.md Shows how to create a `LuaTString`, add it as a global variable, and interact with it from Lua. Modifications made in Lua can be read back into the C++ string object. ```cpp auto str = std::make_shared("hello"); ctx.AddGlobalVariable("greeting", str); ctx.CompileStringAndRun("print(greeting)"); std::cout << str->getValue(); // can read modifications from Lua ``` -------------------------------- ### Get LuaCpp Version Information Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/10-version-and-utilities.md Demonstrates how to retrieve the full version string and its major, minor, and patch components using the LuaCpp::getVersion and related methods. ```cpp std::string getVersion() std::string getMajorVersion() std::string getMinorVersion() std::string getPatchVersion() ``` ```cpp #include #include int main() { std::cout << "LuaCpp version: " << LuaCpp::getVersion() << std::endl; std::cout << "Major: " << LuaCpp::getMajorVersion() << std::endl; std::cout << "Minor: " << LuaCpp::getMinorVersion() << std::endl; std::cout << "Patch: " << LuaCpp::getPatchVersion() << std::endl; return 0; } ``` -------------------------------- ### Execute Scripts with Predefined Pool Configurations Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/1-introduction.md Shows how to use `RunPooled()` with different predefined pool 'colors' to control library access for script execution. For example, 'sandboxed' restricts access, while 'io' enables file operations. ```c++ // Use different pools for different requirements ctx.RunPooled("untrusted_code", "sandboxed"); // No io/os access ctx.RunPooled("file_operation", "io"); // Has io and os ``` -------------------------------- ### Compilation Flags for LuaCpp Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/10-version-and-utilities.md These are example compilation flags for building a project that uses LuaCpp. They include necessary include paths for LuaCpp and Lua, and specify the C++ standard and libraries to link. ```bash # Include paths -I/usr/local/include/LuaCpp -I/usr/include/lua5.3 # Link libraries -lluacpp -llua5.3 # C++ standard -std=c++17 ``` -------------------------------- ### Lua Object with Integer Keys in C++ Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/08-metaobjects.md Implement a C++ class to be used as an array-like object in Lua, supporting integer key access. This example demonstrates setting and getting values by index. ```cpp class LuaArray : public LuaMetaObject { public: std::vector items; LuaArray() : items(10, 0.0) {} std::shared_ptr getValue(int key) override { if (key >= 1 && key <= (int)items.size()) { return std::make_shared(items[key - 1]); } return std::make_shared(); } void setValue(int key, std::shared_ptr val) override { if (key >= 1 && key <= (int)items.size()) { if (auto num = std::dynamic_pointer_cast(val)) { items[key - 1] = num->getValue(); } } } }; int main() { LuaContext ctx; auto arr = std::make_shared(); ctx.AddGlobalVariable("arr", arr); ctx.CompileStringAndRun(R"( arr[1] = 10 arr[2] = 20 arr[3] = 30 print(arr[1] + arr[2] + arr[3]) -- prints 60 )"); return 0; } ``` -------------------------------- ### Example Lua C Function: Add Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/05-luacfunction.md This C function takes two numbers from the Lua stack, adds them, pushes the result back, and returns 1. ```cpp static int add(lua_State *L) { double a = luaL_checknumber(L, 1); // 1st argument double b = luaL_checknumber(L, 2); // 2nd argument lua_pushnumber(L, a + b); // Push result return 1; // Return 1 value } ``` -------------------------------- ### Registering a C Library with a Sum Function in LuaContext Source: https://github.com/jordanvrtanoski/luacpp/blob/main/README.md Demonstrates how to register a custom C function (_sum) as a library named 'foolib' within a LuaContext. The _sum function calculates the sum of numerical arguments passed from Lua. This example also shows how to compile and run Lua code that calls the registered function. ```c++ #include #include #include using namespace LuaCpp; using namespace LuaCpp::Registry; using namespace LuaCpp::Engine; extern "C" { static int _sum (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ lua_Number sum = 0.0; int i; for (i = 1; i <= n; i++) { if (!lua_isnumber(L, i)) { lua_pushliteral(L, "incorrect argument"); lua_error(L); } sum += lua_tonumber(L, i); } lua_pushnumber(L, sum); /* second result */ return 1; /* number of results */ } } int main(int argc, char **argv) { // Creage Lua context LuaContext lua; // Create library "foolib" containing the "sum" function std::shared_ptr lib = std::make_shared("foolib"); lib->AddCFunction("sum", _sum); // Add library to the context lua.AddLibrary(lib); // Run the context try { lua.CompileStringAndRun("print(\"Result of calling foolib.sum(1,2,3,4) = \" .. foolib.sum(1,2,3,4))"); } catch (std::runtime_error& e) { std::cout << e.what() << '\n'; } } ``` -------------------------------- ### Example: Custom Object Inheriting LuaTUserData Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/02-types.md Demonstrates how to create a custom C++ object that inherits from LuaTUserData. This involves overriding protected methods to manage data storage and retrieval between C++ and Lua. ```cpp class MyObject : public LuaMetaObject { protected: void _storeData() override { // Copy C++ object state into Lua buffer } void _retreiveData() override { // Read from Lua buffer back into C++ object } public: // Implement getValue/setValue for Lua field access }; ``` -------------------------------- ### Access LuaState via Pointer or Get Method Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/06-statepool.md Provides methods to access the underlying LuaState object as a pointer, either through the arrow operator or the get() method. ```cpp LuaState* operator->() const LuaState* operator->() const LuaState* get() const const LuaState* get() const ``` -------------------------------- ### Example: Custom Map Implementation with LuaMetaObject Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/02-types.md This example shows a concrete implementation of LuaMetaObject for a C++ map. It overrides getValue and setValue to provide Lua access to the map's string-keyed integer values. ```cpp class MyMap : public LuaMetaObject { public: std::map data; std::shared_ptr getValue(std::string &key) override { if (data.count(key)) { return std::make_shared(data[key]); } return std::make_shared(); } void setValue(std::string &key, std::shared_ptr val) override { if (auto num = std::dynamic_pointer_cast(val)) { data[key] = (int)num->getValue(); } } }; ``` -------------------------------- ### getName / setName Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/07-registry.md Allows getting or setting the name of the Lua code snippet. ```APIDOC ## getName / setName ### Description Allows getting or setting the name of the Lua code snippet. ### Method `std::string getName()` `void setName(std::string name)` ### Parameters #### getName None #### setName - **name** (`std::string`) - The name to set for the snippet. ### Return - `getName()`: The current name of the snippet. - `setName()`: None. ``` -------------------------------- ### Configuring and Using Lua State Pooling Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/README.md Demonstrates how to configure a state pool with specific settings and then use it for fast Lua task execution or manual state management. ```cpp PoolConfig poolConfig; poolConfig.SetMaxSize(10).SetExhaustionTimeoutMs(5000); auto& pool = ctx.createPool("workers", poolConfig); // Fast execution using pooled states ctx.RunPooled("task", "workers"); // Or manual control auto state = ctx.AcquirePooledState("workers"); // Use state... ctx.ReleasePooledState(std::move(state), "workers"); ``` -------------------------------- ### Get Lua Bytecode Buffer Size Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/07-registry.md Returns the size of the bytecode buffer in bytes. ```cpp int getSize() ``` -------------------------------- ### LuaLibrary Information Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/03-lualibrary.md Methods to get or set the library name, and to retrieve the meta-table name. ```APIDOC ## LuaLibrary Information ### getName ```cpp std::string getName() ``` Get the library name. ### setName ```cpp void setName(const std::string &name) ``` Set the library name. ### getMetaTableName ```cpp std::string getMetaTableName() ``` Get the meta-table name for this library. ``` -------------------------------- ### Table::Key Constructors Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/02-types.md Illustrates the constructors for Table::Key, showing how to create keys from integers and strings. ```cpp explicit Key(int value) // Integer key explicit Key(std::string value) // String key explicit Key(const char *value) // String key (C string) ``` -------------------------------- ### Warmup Lua State Pool Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/dcp/DCP-002-lua-state-pooling.md Demonstrates how to pre-create a specified number of Lua states in a pool to avoid allocation overhead during subsequent `AcquirePooledState` calls. ```cpp LuaContext ctx; // Pre-create all states in pool auto& pool = ctx.getPool("default"); pool.warmup(5); // Create 5 states upfront // Now all AcquirePooledState calls are allocation-free ``` -------------------------------- ### Create Lua Context Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/09-api-summary.md Instantiate the main entry point for LuaCpp interactions. ```cpp LuaCpp::LuaContext ctx; ``` -------------------------------- ### Get and Set LuaCodeSnippet Name Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/07-registry.md Allows retrieving or setting the name associated with the Lua code snippet. ```cpp std::string getName() void setName(std::string name) ``` -------------------------------- ### Run Unit Tests and Debug Source: https://github.com/jordanvrtanoski/luacpp/blob/main/README.md Configure the build with Debug type using CMake, then build and run the unit tests. ```bash mkdir build cd build cmake -DCMAKE_BUILD_TYPE=Debug ../Source make -j$(nproc) make test ``` -------------------------------- ### Get Named State Pool Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/06-statepool.md Retrieves a reference to a specific StatePool by its name. Throws std::runtime_error if the pool does not exist. ```cpp StatePool& getPool(const std::string& color) ``` -------------------------------- ### Get Standard Lua Library Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/01-luacontext.md Retrieves a standard Lua library (e.g., 'math', 'string') by name, allowing for modification. ```cpp std::shared_ptr getStdLibrary(const std::string &libName) ``` -------------------------------- ### Add Doxygen Custom Target Source: https://github.com/jordanvrtanoski/luacpp/blob/main/Source/CMakeLists.txt Creates a custom target to generate API documentation using Doxygen. Requires Doxygen to be installed. ```cmake add_custom_target( doc_doxygen COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_OUT} WORKING_DIRECTORY ${PROJECT_BINARY_DIR} COMMENT "Generating API documentation with Doxygen" VERBATIM ) add_custom_target( doc_pdf COMMAND cd doc_doxygen/latex && make pdf COMMAND mv doc_doxygen/latex/refman.pdf ${CMAKE_BINARY_DIR}/luacpp.pdf DEPENDS doc_doxygen ) ``` -------------------------------- ### Create and Use Custom Lua State Pools Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/1-introduction.md Illustrates how to define a custom pool configuration with specific libraries and a maximum size, then create and use this pool for script execution. This allows fine-grained control over available Lua modules. ```c++ LuaContext ctx; PoolConfig config; config.libraries = {"base", "math"}; config.maxSize = 3; ctx.createPool("math_only", config); ctx.RunPooled("calculation", "math_only"); ``` -------------------------------- ### Create and Use a Named Pool Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/06-statepool.md Demonstrates creating a new 'workers' pool with specific configurations and then accessing it. ```cpp PoolManager& manager = ctx.getPoolManager(); PoolConfig workerCfg; workerCfg.SetMaxSize(15).SetLibraries({"math", "string"}); manager.createPool("workers", workerCfg); StatePool& pool = manager.getPool("workers"); ``` -------------------------------- ### Find LuaCpp Package Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/10-version-and-utilities.md Use this CMake command to find the LuaCpp package in your project. Ensure LuaCpp is installed and discoverable by CMake. ```cmake find_package(LuaCpp REQUIRED) ``` -------------------------------- ### warmup Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/06-statepool.md Pre-creates a specified number of Lua states in the pool to improve acquisition performance. ```APIDOC ## warmup ### Description Pre-allocates a specified number of Lua states in the pool. ### Method `warmup(size_t n)` ### Endpoint N/A (Method Call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```cpp pool.warmup(10); ``` ### Response N/A ### Behavior Creates `n` new states and adds them to the pool, making them immediately available for acquisition. ``` -------------------------------- ### LuaState StateParams Usage Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/04-luastate.md Demonstrates how to set up custom allocator parameters for creating a new Lua state. ```cpp LuaCpp::Engine::StateParams params; params.allocator = myAllocator; params.userData = allocatorContext; auto state = ctx.newState(params); ``` -------------------------------- ### Fluent Configuration for PoolConfig Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/2-state-pooling.md Shows how to configure a PoolConfig object using method chaining for a more concise syntax. This is useful for setting multiple configuration options in a single statement. ```cpp PoolConfig config; config.SetLibraries({"base", "math"}) .SetMaxSize(3) .AddGlobalVariable("debug", std::make_shared(true)); ``` -------------------------------- ### Inspect Lua Stack with LuaCpp Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/10-version-and-utilities.md Demonstrates how to create a new Lua state and print its current stack contents using LuaCpp. ```cpp auto state = ctx.newState(); lua_pushstring(*state, "test"); state->PrintStack(std::cout); // Shows: Stack (top=1): [1]=string: "test" ``` -------------------------------- ### Configure Custom Lua State Pool Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/dcp/DCP-002-lua-state-pooling.md Shows how to create a custom Lua state pool with specific configurations, including allowed libraries, global variables, maximum size, and exhaustion timeout. ```cpp LuaContext ctx; PoolConfig config; config.libraries = {"base", "math"}; config.globalVariables["version"] = std::make_shared("1.0"); config.maxSize = 3; config.exhaustionTimeoutMs = 5000; // 5 second timeout ctx.createPool("math_only", config); ctx.CompileString("calc", "return math.sqrt(16)"); ctx.RunPooled("calc", "math_only"); ``` -------------------------------- ### Get Global Lua Variable Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/01-luacontext.md Retrieves a global Lua variable by its name from the context. Returns a shared pointer to the LuaType or nullptr if not found. ```cpp std::shared_ptr getGlobalVariable(const std::string &name) ``` -------------------------------- ### Efficient Lua Code Execution with Caching Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/README.md Demonstrates compiling Lua code once and then executing it multiple times for performance gains. ```cpp // Compile once (expensive) ctx.CompileString("worker", "for i=1,1000000 do sum = sum + i end"); // Execute many times (fast) for (int i = 0; i < 100; i++) { ctx.Run("worker"); } ``` -------------------------------- ### Get Lua Bytecode Buffer Pointer Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/07-registry.md Provides low-level access to the raw binary bytecode buffer. Useful for serialization or debugging purposes. ```cpp const char *getBuffer() ``` -------------------------------- ### LuaTString Type Definition Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/02-types.md Represents Lua strings as C++ `std::string`. It inherits from `LuaType` and allows getting and setting the string value. ```cpp class LuaTString : public LuaType ``` -------------------------------- ### LuaRegistry Constructor Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/07-registry.md Initializes an empty LuaRegistry. ```APIDOC ## LuaRegistry() ### Description Initializes an empty registry. ### Method Constructor ### Parameters None ``` -------------------------------- ### RAII-Style Lua State Management Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/dcp/DCP-002-lua-state-pooling.md Demonstrates RAII (Resource Acquisition Is Initialization) for managing pooled Lua states. The state is automatically returned to the pool when the scope ends. ```cpp LuaContext ctx; { auto pooled = ctx.AcquirePooledStateRAII("default"); // Use *pooled or pooled.get() lua_pushstring(*pooled, "test"); // State automatically returns to pool at end of scope } ``` -------------------------------- ### Callable Lua Object in C++ Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/08-metaobjects.md Implement a C++ class that can be called like a function from Lua. This example shows how to handle arguments and return values. ```cpp class LuaCallable : public LuaMetaObject { public: int value = 10; int Execute(LuaState &L) override { // Get argument count int argc = lua_gettop(L); if (argc > 0 && lua_isnumber(L, 1)) { int multiplier = (int)lua_tonumber(L, 1); lua_pushnumber(L, value * multiplier); return 1; // Return 1 value } lua_pushnumber(L, value); return 1; // Return 1 value } }; int main() { LuaContext ctx; auto obj = std::make_shared(); obj->value = 5; ctx.AddGlobalVariable("callable", obj); ctx.CompileStringAndRun(R"( print(callable()) -- prints 5 print(callable(3)) -- prints 15 )"); return 0; } ``` -------------------------------- ### Pre-warming a StatePool Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/06-statepool.md Initializes a StatePool by creating a specified number of Lua states upfront to avoid delays during initial acquisitions. ```cpp auto& pool = ctx.getPool("default"); pool.warmup(10); // Create 10 states upfront ``` -------------------------------- ### Manage Lua State Pools Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/01-luacontext.md Provides functions to get, check for, or create Lua state pools. Pools are identified by a 'color' name and can be configured. ```cpp Engine::StatePool& getPool(const std::string& color = "default") bool hasPool(const std::string& color) Engine::StatePool& createPool(const std::string& color, const Engine::PoolConfig& config) ``` -------------------------------- ### Retrieve Internal Library Methods/Functions Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/03-lualibrary.md Provides signatures for retrieving C function pointers by name. These are typically used internally by LuaContext during state setup. ```cpp lua_CFunction getLibMethod(const std::string &name) ``` ```cpp lua_CFunction getLibFunction(const std::string &name) ``` -------------------------------- ### Expose C++ Object to Lua as Meta-Object Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/README.md Defines a C++ class inheriting from LuaMetaObject to expose object properties to Lua. This example shows accessing a setting. ```cpp class MyObject : public LuaMetaObject { std::map data; public: std::shared_ptr getValue(std::string &key) override { if (data.count(key)) { return std::make_shared(data[key]); } return std::make_shared(); } }; auto obj = std::make_shared(); ctx.AddGlobalVariable("config", obj); ctx.CompileStringAndRun("print(config.setting)"); ``` -------------------------------- ### Warmup State Pool Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/2-state-pooling.md Pre-create a specified number of states in a pool to eliminate allocation overhead during subsequent state acquisitions. Call this after getting a reference to the pool. ```cpp StatePool& pool = ctx.getPool("default"); pool.warmup(5); // Create 5 states upfront // Now all AcquirePooledState() calls will be allocation-free ``` -------------------------------- ### Create Custom Lua Pool with PoolConfig Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/2-state-pooling.md Demonstrates creating a custom Lua state pool named 'math_only' with specific libraries, maximum size, and a global variable. Use this when you need a pool with a restricted set of functionalities or pre-defined global values. ```cpp LuaContext ctx; PoolConfig config; config.libraries = {"base", "math"}; config.maxSize = 3; config.AddGlobalVariable("app_version", std::make_shared("1.0.0")); StatePool& pool = ctx.createPool("math_only", config); ctx.CompileString("calc", "print(math.sqrt(100) .. ' (v' .. app_version .. ')')"); ctx.RunPooled("calc", "math_only"); ``` -------------------------------- ### Execute Scripts with Different Pool Colors Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/2-state-pooling.md Shows how to execute scripts using specific pool configurations identified by colors. This allows for different sets of libraries and global variables to be available for each execution. ```cpp LuaContext ctx; ctx.CompileString("calc", "result = math.sqrt(144)"); ctx.CompileString("file_op", "f = io.open('data.txt', 'r')"); // Execute on sandboxed pool (has math, no io) ctx.RunPooled("calc", "sandboxed"); // Execute on io pool (has io and os) ctx.RunPooled("file_op", "io"); ``` -------------------------------- ### Get State Pool Manager Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/01-luacontext.md Retrieves a reference to the pool manager, which is lazily initialized on first access. The manager handles multiple named state pools. ```cpp Engine::PoolManager& getPoolManager() ``` -------------------------------- ### Get or Set Built-in Lua Function Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/01-luacontext.md Allows retrieval or setting of global Lua functions using the lua_CFunction interface. Useful for overriding standard functions. ```cpp std::shared_ptr getBuiltInFnc(const std::string &fncName) ``` ```cpp void setBuiltInFnc(const std::string &fncName, lua_CFunction cfunction) ``` ```cpp void setBuiltInFnc(const std::string &fncName, lua_CFunction cfunction, bool replace) ``` -------------------------------- ### Configure Lua Pool Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/09-api-summary.md Sets up a Lua execution pool with specific configurations like maximum size, timeouts, libraries, global variables, and hooks. ```cpp PoolConfig cfg; cfg .SetMaxSize(10) .SetExhaustionTimeoutMs(5000) .SetLibraries({"math", "string"}) .AddGlobalVariable("setting", std::make_shared(42)) .AddHook(hookType, count, hookFunc); auto& pool = ctx.createPool("workers", cfg); ``` -------------------------------- ### LuaTString Type Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/02-types.md Represents Lua strings as C++ `std::string`. It allows for getting and setting the string value, and modifications made in C++ can be reflected in Lua. ```APIDOC ## LuaTString Type ### Description Represents Lua strings as C++ `std::string`. ### Constructors ```cpp explicit LuaTString(std::string _value) ``` ### Methods | Method | Return | Description | |--------|--------|-------------| | `getValue() const` | `std::string` | Get the string value | | `setValue(std::string value)` | `void` | Set the string value | ### Example ```cpp auto str = std::make_shared("hello"); ctx.AddGlobalVariable("greeting", str); ctx.CompileStringAndRun("print(greeting)"); std::cout << str->getValue(); // can read modifications from Lua ``` ``` -------------------------------- ### PoolManager Class Definition Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/dcp/DCP-002-lua-state-pooling.md Manages multiple colored Lua state pools. It provides methods to get, create, destroy, and check for the existence of pools, and to control thread safety. ```cpp PoolManager { pools: map> threadSafe: bool getPool(color) -> StatePool& createPool(color, config) -> StatePool& destroyPool(color) hasPool(color) -> bool listPools() -> vector setThreadSafe(bool) } ``` -------------------------------- ### Configure Libraries for State Pool Source: https://github.com/jordanvrtanoski/luacpp/blob/main/_autodocs/06-statepool.md Sets the libraries to be loaded into each state within the pool. Use this to pre-load common Lua modules. ```cpp PoolConfig cfg; cfg.SetLibraries({"math", "string", "table"}); ``` -------------------------------- ### Convenience Pool Access Methods Source: https://github.com/jordanvrtanoski/luacpp/blob/main/docs/dcp/DCP-002-lua-state-pooling.md Provides convenient methods to access existing pools by color, create new pools with specified configurations, and check if a pool exists. ```cpp // Convenience methods StatePool& getPool(const std::string& color = "default"); StatePool& createPool(const std::string& color, const PoolConfig& config); bool hasPool(const std::string& color); ```