### Install LuaBridge3 with vcpkg Source: https://kunitoki.github.io/LuaBridge3 Use the vcpkg package manager to download and install LuaBridge3. Ensure vcpkg is set up correctly before running the install command. ```powershell git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh # The name of the script should be “./bootstrap-vcpkg.bat” for Powershell ./vcpkg integrate install ./vcpkg install luabridge3 ``` -------------------------------- ### Lua Usage Examples for Registered Classes Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates interacting with static members, instance members, and garbage collection behavior in Lua. ```lua print (test.A.staticData) -- Prints the static data member. print (test.A.staticProperty) -- Prints the static property member. test.A.staticFunc () -- Calls the static method. print (a.data) -- Prints the data member. print (a.prop) -- Prints the property member. a:func1 () -- Calls A::func1 (). test.A.func1 (a) -- Equivalent to a:func1 (). test.A.func1 ("hello") -- Error: "hello" is not a class A. a:virtualFunc () -- Calls A::virtualFunc (). print (b.data) -- Prints B::dataMember. print (b.prop) -- Prints inherited property member. b:func1 () -- Calls B::func1 (). b:func2 () -- Calls B::func2 (). test.B.func2 (a) -- Error: a is not a class B. test.A.func1 (b) -- Calls A::func1 (). b:virtualFunc () -- Calls B::virtualFunc (). test.B.virtualFunc (b) -- Calls B::virtualFunc (). test.A.virtualFunc (b) -- Calls B::virtualFunc (). test.B.virtualFunc (a) -- Error: a is not a class B. a = nil; collectgarbage () -- 'a' still exists in C++. b = nil; collectgarbage () -- Lua calls ~B() on the copy of b. ``` -------------------------------- ### Strict Mode Boolean Conversion Examples Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates how strict mode rejects non-boolean types during stack retrieval. ```cpp lua_pushinteger (L, 42); auto r = luabridge::Stack::get (L, -1); // error: not a boolean lua_pushnil (L); auto r = luabridge::Stack::get (L, -1); // error: not a boolean lua_pushstring (L, "hello"); auto r = luabridge::Stack::get (L, -1); // error: not a boolean lua_pushboolean (L, 1); auto r = luabridge::Stack::get (L, -1); // ok: true ``` -------------------------------- ### Define C++ Classes for LuaBridge Source: https://kunitoki.github.io/LuaBridge3/Manual Example structures A and B demonstrating static members, data properties, and virtual functions. ```cpp struct A { static int staticData; static float staticProperty; static float getStaticProperty () { return staticProperty; } static void setStaticProperty (float f) { staticProperty = f; } static void staticFunc () { } static int staticCFunc (lua_State *L) { return 0; } std::string dataMember; char dataProperty; char getProperty () const { return dataProperty; } void setProperty (char v) { dataProperty = v; } std::string toString () const { return dataMember; } void func1 () { } virtual void virtualFunc () { } int cfunc (lua_State* L) { return 0; } }; struct B : public A { double dataMember2; void func1 () { } void func2 () { } void virtualFunc () { } }; int A::staticData; float A::staticProperty; ``` -------------------------------- ### Custom Stack Specialization for juce::String Source: https://kunitoki.github.io/LuaBridge3/Manual Example implementation of a Stack specialization to support custom user-defined types. ```cpp namespace luabridge { template <> struct Stack { static Result push (lua_State* L, const juce::String& s) { lua_pushstring (L, s.toUTF8 ()); return {}; } static TypeResult get (lua_State* L, int index) { if (lua_type (L, index) != LUA_TSTRING) return makeErrorCode (ErrorCode::InvalidTypeCast); std::size_t length = 0; const char* str = lua_tolstring (L, index, &length); if (str == nullptr) return makeErrorCode (ErrorCode::InvalidTypeCast); return juce::String::fromUTF8 (str); } static bool isInstance (lua_State* L, int index) { return lua_type (L, index) == LUA_TSTRING; } }; } // namespace luabridge ``` -------------------------------- ### Appending to Lua Sequence Tables Source: https://kunitoki.github.io/LuaBridge3/Manual Shows how to use the append method to add one or more values to the end of a Lua sequence table. This is equivalent to assigning to sequential integer keys starting from #t + 1. ```cpp luabridge::LuaRef t = luabridge::newTable (L); t.append (1); // t = {1} t.append (2, 3); // t = {1, 2, 3} t.append ("hello", true); // t = {1, 2, 3, "hello", true} ``` -------------------------------- ### Registering Index and New Index Metamethods in C++ Source: https://kunitoki.github.io/LuaBridge3/Manual Shows how to implement both index and newindex fallbacks to manage a dynamic property map. ```cpp struct FlexibleClass { std::unordered_map properties; }; luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginClass ("FlexibleClass") .addIndexMetaMethod ([] (FlexibleClass& self, const luabridge::LuaRef& key, lua_State* L) { auto it = self.properties.find(key); if (it != self.properties.end()) return it->second; return luabridge::LuaRef (L, luabridge::LuaNil ()); // or luaL_error("Failed lookup of key !") }) .addNewIndexMetaMethod ([] (FlexibleClass& self, const luabridge::LuaRef& key, const luabridge::LuaRef& value, lua_State* L) { self.properties.emplace (std::make_pair (key, value)) return luabridge::LuaRef (L, luabridge::LuaNil ()); }) .endClass () .endNamespace (); FlexibleClass flexi; luabridge::pushGlobal (L, &flexi, "flexi"); ``` -------------------------------- ### Constructing LuaRef Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates initializing LuaRef with nil or specific primitive values. ```cpp luabridge::LuaRef v (L); // References nil ``` ```cpp luabridge::LuaRef v1 (L, 1); // A LUA_TNUMBER luabridge::LuaRef v2 (L, 1.1); // Also a LUA_TNUMBER luabridge::LuaRef v3 (L, true); // A LUA_TBOOLEAN luabridge::LuaRef v4 (L, "string"); // A LUA_TSTRING ``` -------------------------------- ### Create a custom namespace Source: https://kunitoki.github.io/LuaBridge3/Manual Adds a new namespace table to the global environment. ```cpp luabridge::getGlobalNamespace (L) .beginNamespace ("test"); ``` -------------------------------- ### Constructor Registration Source: https://kunitoki.github.io/LuaBridge3/Manual Explains how to register constructors for C++ classes, allowing them to be instantiated from Lua. ```APIDOC ## Registering Constructors ### Description This section details how to register constructors for C++ classes, enabling the creation of class instances directly from Lua code. Unlike functions, constructor signatures must be explicitly provided. ### Method `addConstructor` ### Endpoint N/A (C++ API) ### Parameters - **`addConstructor`**: The template arguments specify the signatures of the constructors to be registered. The return type is always `void` for constructors. ### Request Example ```cpp struct A { A (); A (std::string_view a); A (std::string_view a, int b); }; luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginClass ("A") .addConstructor () .endClass () .endNamespace (); ``` ### Request Example (Lua) ```lua a = test.A () -- Creates an instance using the default constructor. b = test.A ("hello", 5) -- Creates an instance using the constructor with string and int. ``` ### Response N/A (C++ API registration) ### Error Handling - If a constructor call from Lua does not match any of the registered signatures, a Lua error will occur. - Constructors are called using the fully qualified class name in Lua (e.g., `namespace.ClassName(...)`). ``` -------------------------------- ### Stack Traits Get Method Source: https://kunitoki.github.io/LuaBridge3/Manual Retrieves a C++ value from the Lua stack at a given index. Returns a TypeResult containing the value or an error. ```cpp /// Converts the Lua value at the index into the C++ value of the type T. TypeResult get (lua_State* L, int index); ``` -------------------------------- ### Registering Functions in a Namespace Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates how to register functions within a namespace, showing two equivalent methods for adding multiple functions. ```cpp luabridge::getGlobalNamespace (L) .beginNamespace ("test") .addFunction ("foo", foo) .endNamespace (); luabridge::getGlobalNamespace (L) .beginNamespace ("test") .addFunction ("bar", bar) .endNamespace (); ``` ```cpp luabridge::getGlobalNamespace (L) .beginNamespace ("test") .addFunction ("foo", foo) .addFunction ("bar", bar) .endNamespace (); ``` -------------------------------- ### Custom Stack Specialization for Array Source: https://kunitoki.github.io/LuaBridge3/Manual Implement custom push and get logic for Array to handle potential errors and maintain stack integrity. This is crucial when exceptions are disabled. ```cpp namespace luabridge { template struct Stack> { static Result push (lua_State* L, const Array& array) { const int initialStackSize = lua_gettop (L); lua_createtable (L, static_cast (array.size ()), 0); for (std::size_t i = 0; i < array.size (); ++i) { lua_pushinteger (L, static_cast (i + 1)); auto result = Stack::push (L, array[i]); if (! result) { lua_pop (L, lua_gettop (L) - initialStackSize); return result; } lua_settable (L, -3); } return {}; } static TypeResult> get (lua_State* L, int index) { if (!lua_istable (L, index)) return makeErrorCode (ErrorCode::InvalidTypeCast); const int initialStackSize = lua_gettop (L); Array a; a.reserve (static_cast (get_length(L, index))); const int absIndex = lua_absindex (L, index); lua_pushnil (L); while (lua_next (L, absIndex) != 0) { auto item = Stack::get (L, -1); if (! item) { lua_pop (L, lua_gettop (L) - initialStackSize); return item.error (); } a.append (*item); lua_pop (L, 1); } return a; } }; } // namespace luabridge ``` -------------------------------- ### Nest multiple namespaces Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates creating a hierarchy of nested namespaces using the fluent interface. ```cpp luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginNamespace ("detail") .endNamespace () .beginNamespace ("utility") .endNamespace () .endNamespace (); ``` -------------------------------- ### Global Options Reference Source: https://kunitoki.github.io/LuaBridge3/Manual Defines registration options for classes and namespaces. ```cpp /// Flag set of options class Options : FlagSet; /// Default options for classes / namespaces registration. Option defaultOptions; /// Specify that class methods should allow to the extended by lua scripts. Option extensibleClass; /// Allow an extensible class to overriding C++ exposed methods. Option allowOverridingMethods; /// Allow access to class / namespace metatables. Option visibleMetatables; ``` -------------------------------- ### Update vcpkg port for LuaBridge3 Source: https://kunitoki.github.io/LuaBridge3 Steps to update the LuaBridge3 port in vcpkg. This involves getting the latest commit hash, downloading the artifact, calculating its SHA512 checksum, and updating the relevant files in the vcpkg repository. ```bash COMMIT_HASH=$(git rev-parse HEAD) wget https://github.com/kunitoki/LuaBridge3/archive/${COMMIT_HASH}.tar.gz shasum -a 512 ${COMMIT_HASH}.tar.gz # fbdf09e3bd0d4e55c27afa314ff231537b57653b7c3d96b51eac2a41de0c302ed093500298f341cb168695bae5d3094fb67e019e93620c11c7d6f8c86d3802e2 0e17140276d215e98764813078f48731125e4784.tar.gz ``` ```bash ./vcpkg x-add-version --all ``` -------------------------------- ### Registering Properties and Functions in C++ Source: https://kunitoki.github.io/LuaBridge3/Manual Illustrates registering various C++ variables, properties, and functions into a Lua namespace. Properties can be read-only or read-write. ```cpp luabridge::getGlobalNamespace (L) .beginNamespace ("test") .addProperty ("var1", &globalVar) // read-only .addProperty ("var2", &staticVar, &staticVar) // read-write .addProperty ("prop1", getString) // read-only .addProperty ("prop2", getString, setString) // read-write .addProperty ("tup1", &tuple) // read-only .addProperty ("tup2", &tuple, &tuple) // read-write .addFunction ("foo", foo) .addFunction ("bar", bar) .addFunction ("cfunc", cFunc) .endNamespace (); ``` -------------------------------- ### Invoking Constructors in Lua Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates how to instantiate registered C++ classes within the Lua environment. ```lua a = test.A () -- Create a new A. b = test.B ("hello", 5) -- Create a new B. b = test.B () -- Error: expected string in argument 1 ``` -------------------------------- ### Static Metamethods Lua Usage Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates interacting with static class properties via the registered metamethods in Lua. ```lua MyClass.dynamicProp = 42 value = MyClass.dynamicProp assert (value == 42, "Value stored via static __newindex fallback and retrieved via static __index fallback") missing = MyClass.nonExistingKey assert (missing == nil, "Unknown key returns nil through the static __index fallback") ``` -------------------------------- ### Managing LuaRef Assignments and Nil Source: https://kunitoki.github.io/LuaBridge3/Manual Shows how LuaRef handles variable assignment and explicit nil assignment using LuaNil. ```cpp luabridge::LuaRef v1 (L, "x"); // assign "x" luabridge::LuaRef v2 (L, "y"); // assign "y" v2 = v1; // v2 becomes "x" v1 = "z"; // v1 becomes "z", v2 is unchanged v1 = luabridge::newTable (L); // An empty table v2 = v1; // v2 references the same table as v1 v1 = luabridge::LuaNil (); // v1 becomes nil, table is still referenced by v2. ``` -------------------------------- ### Calling Lua Functions from C++ Source: https://kunitoki.github.io/LuaBridge3/Manual Illustrates how to retrieve a global Lua function named 'same' and prepare to call it from C++. The return value is a LuaRef, which can be nil. ```lua function same (arg1, arg) return arg1 == arg2 end ``` ```cpp luabridge::LuaRef same = luabridge::getGlobal (L, "same"); ``` -------------------------------- ### Registering Functions and Properties from Stack Table Source: https://kunitoki.github.io/LuaBridge3/Manual Shows how to obtain a namespace from a table on the Lua stack and register functions and properties into it. ```cpp lua_newtable (L); luabridge::getNamespaceFromStack (L) .addFunction ("test", +[] (int x) { return x; }) .addFunction ("bar", &bar); ``` -------------------------------- ### Function Overloading Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates how to register multiple functions with the same name to handle different argument types and arities. ```APIDOC ## Registering Overloaded Functions ### Description This section explains how to register multiple functions or methods with the same name in LuaBridge. LuaBridge will attempt to match the Lua call to the registered overloads based on the arguments provided. ### Method `addFunction`, `addStaticFunction`, `overload`, `constOverload`, `nonConstOverload` ### Endpoint N/A (C++ API) ### Parameters - **`luabridge::overload`**: Used to specify the signature of an overload. The template arguments define the C++ parameter types. - **`luabridge::constOverload`**: Similar to `overload`, but specifically for const member functions. - **`luabridge::nonConstOverload`**: Similar to `overload`, but specifically for non-const member functions. ### Request Example ```cpp struct Vec { void rotate (float degrees); void rotate (const Quat& quaternion); }; luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginClass ("Vec") .addFunction ("rotate", luabridge::overload (&Vec::rotate), luabridge::overload (&Vec::rotate)) .endClass () .endNamespace (); ``` ### Response N/A (C++ API registration) ### Error Handling - If no overload matches the arguments provided in the Lua call, an error will be raised in Lua. - The order of overloads matters; LuaBridge tries them from first to last. ``` -------------------------------- ### Generate VS2019 Solution on Windows Source: https://kunitoki.github.io/LuaBridge3 Use this command to generate a Visual Studio 2019 solution for building the project on Windows. The generated solution file will be located in the build directory. ```bash git clone --recursive git@github.com:kunitoki/LuaBridge3.git mkdir LuaBridge3/build pushd LuaBridge3/build cmake -G "Visual Studio 16" ../ # Generates MSVS solution build/LuaBridge.sln popd ``` -------------------------------- ### Registering an Index Metamethod Fallback in C++ Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates using addIndexMetaMethod to handle dynamic property access for a C++ struct. ```cpp struct FlexibleClass { int propertyOne = 42; }; luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginClass ("FlexibleClass") .addProperty ("propertyOne", &FlexibleClass::propertyOne, &FlexibleClass::propertyOne) .addIndexMetaMethod ([] (FlexibleClass& self, const luabridge::LuaRef& key, lua_State* L) { if (key.tostring () == "existingProperty") return luabridge::LuaRef (L, 1337); return luabridge::LuaRef (L, luabridge::LuaNil ()); // or luaL_error("Failed lookup of key !") }) .endClass () .endNamespace (); FlexibleClass flexi; luabridge::pushGlobal (L, &flexi, "flexi"); ``` -------------------------------- ### Constructor Registration Source: https://kunitoki.github.io/LuaBridge3/Manual APIs for registering constructors for a class. ```APIDOC ## Constructor Registration ### Description Registers constructors for a C++ class, allowing instantiation from Lua. ### Methods #### `addConstructor ()` Registers one or multiple overloaded constructors. #### `addConstructor (Functions... functions)` Registers one or multiple overloaded constructors using callable arguments. #### `addConstructorFrom ()` Registers constructors when usable from an intrusive container. #### `addConstructorFrom (Functions... functions)` Registers constructors from an intrusive container using callable arguments. #### `addFactory (Alloc alloc, Dealloc dealloc)` Registers allocator and deallocator functions for the class. ``` -------------------------------- ### Configuration Options Source: https://kunitoki.github.io/LuaBridge3/Manual These are preprocessor defines that can be used to configure LuaBridge's behavior. ```APIDOC ## Configuration Options ### LUABRIDGE_STRICT_STACK_CONVERSIONS **Default:** `0` (disabled). Enables strict mode for stack conversions, requiring explicit type-safe conversions. In non-strict mode, `lua_toboolean` semantics apply, where all Lua values except `false` and `nil` are truthy. ```cpp #define LUABRIDGE_STRICT_STACK_CONVERSIONS 1 #include ``` ### LUABRIDGE_SAFE_LUA_C_EXCEPTION_HANDLING **Default:** `0` (disabled). Only meaningful when `LUABRIDGE_HAS_EXCEPTIONS` is `1`. Adds a safe indirection to catch C++ exceptions at the `lua_CFunction` boundary and re-raise them as Lua errors. This is useful when compiling Lua as C and observing crashes when registered CFunctions throw exceptions. ```cpp #define LUABRIDGE_SAFE_LUA_C_EXCEPTION_HANDLING 1 #include ``` **Warning:** Enables this flag introduces a small performance overhead on every registered CFunction call. ### LUABRIDGE_RAISE_UNREGISTERED_CLASS_USAGE **Default:** `1` when exceptions are enabled, `0` otherwise. When enabled, using an unregistered class with LuaBridge will raise an error. With exceptions enabled, this translates to a `luabridge::LuaException`; with exceptions disabled, it translates to a Lua error via `lua_error`. ```cpp #define LUABRIDGE_RAISE_UNREGISTERED_CLASS_USAGE 0 #include ``` ``` -------------------------------- ### Register Classes Source: https://kunitoki.github.io/LuaBridge3/Manual Methods for beginning, deriving, and ending class registration in LuaBridge3. ```cpp /// Begins or continues class registration, returns this class object. template Class beginClass (const char* name); /// Begins derived class registration with one or more base classes, returns this class object. template Class deriveClass (const char* name); /// Ends class registration, returns the parent namespace object. template Namespace endClass (); ``` -------------------------------- ### Global Options API Source: https://kunitoki.github.io/LuaBridge3/Manual Defines for global options and default registration settings. ```APIDOC ## Global Options API ### Options Class ```cpp /// Flag set of options class Options : FlagSet; ``` ### Default Options ```cpp /// Default options for classes / namespaces registration. Option defaultOptions; ``` ### Option Flags - **extensibleClass**: Specify that class methods should allow to be extended by lua scripts. - **allowOverridingMethods**: Allow an extensible class to overriding C++ exposed methods. - **visibleMetatables**: Allow access to class / namespace metatables. ``` -------------------------------- ### Creating LuaRef Tables and Globals Source: https://kunitoki.github.io/LuaBridge3/Manual Creates references to new tables or existing global variables in the Lua state. ```cpp luabridge::LuaRef v1 = luabridge::newTable (L); // Create a new table luabridge::LuaRef v2 = luabridge::getGlobal (L, "print") // Reference to _G ["print"] ``` -------------------------------- ### Access the global namespace Source: https://kunitoki.github.io/LuaBridge3/Manual Retrieves the global namespace object to begin registrations. ```cpp luabridge::getGlobalNamespace (L); ``` -------------------------------- ### Register a class factory in C++ Source: https://kunitoki.github.io/LuaBridge3/Manual Use addFactory to specify custom allocator and deallocator functions for a class. ```cpp struct IObject { virtual void overridableMethod () const = 0; }; // These might be defined in a shared library, returning concrete types. extern "C" IObject* objectFactoryAllocator (); extern "C" void objectFactoryDeallocator (IObject*); luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginClass ("Object") .addFactory (&objectFactoryAllocator, &objectFactoryDeallocator) .addFunction ("overridableMethod", &IObject::overridableMethod) .endClass () .endNamespace (); ``` -------------------------------- ### Instantiate a class with a custom constructor in Lua Source: https://kunitoki.github.io/LuaBridge3/Manual Invoke the registered constructor proxy from the Lua side. ```lua hard = test.HardToCreate (5) -- Create a new HardToCreate. ``` -------------------------------- ### Class Registration Source: https://kunitoki.github.io/LuaBridge3/Manual APIs for beginning and ending class registration. ```APIDOC ## Class Registration ### Description Manages the registration process for C++ classes to be exposed to Lua. ### Methods #### `beginClass (const char* name)` Begins or continues class registration. #### `deriveClass (const char* name, class Base1, class... Bases)` Begins derived class registration with one or more base classes. #### `endClass ()` Ends class registration. ``` -------------------------------- ### Registering Custom Container Constructors Source: https://kunitoki.github.io/LuaBridge3/Manual Uses addConstructorFrom with custom lambdas to define how objects are constructed and placed into a container. ```cpp class C : public std::enable_shared_from_this { C () { } C (int) { } }; luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginClass ("C") .addConstructorFrom> ( []() { return std::make_shared (); }, [](int value) { return std::make_shared (value); }) .endClass () .endNamespace () ``` -------------------------------- ### Extend C++ Class with Lua Methods Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates how to add new instance and static methods to a C++ class from Lua. These methods are stored in the class's metatable, enabling runtime extension. ```lua function ExtensibleClass:newInstanceMethod() return self.propertyOne * 2 end function ExtensibleClass.newStaticMethod() return 1337 end print (clazz:newMethod(), ExtensibleClass.newStaticMethod()) ``` -------------------------------- ### Static Metamethod Fallback Priority Source: https://kunitoki.github.io/LuaBridge3/Manual Shows how returning nil from a static index metamethod allows normal lookup of registered static functions to proceed. ```cpp struct MyClass { static int answer () { return 42; } }; luabridge::getGlobalNamespace (L) .beginClass ("MyClass") .addStaticFunction ("answer", &MyClass::answer) .addStaticIndexMetaMethod ([] (const luabridge::LuaRef& /*key*/, lua_State* L) -> luabridge::LuaRef { // Returning nil lets the registered static function be found normally return luabridge::LuaRef (L, luabridge::LuaNil ()); }) .endClass (); ``` -------------------------------- ### Register Class Metamethods in C++ Source: https://kunitoki.github.io/LuaBridge3/Manual Use these methods to define fallback index and newindex handlers for class instances or static tables. ```cpp /// Registers a fallback __index handler for instances (called when a key is not found). template Class addIndexMetaMethod (Function function); /// Registers a fallback __newindex handler for instances (called when a key is not found). template Class addNewIndexMetaMethod (Function function); /// Registers a fallback __index handler for the static class table. template Class addStaticIndexMetaMethod (Function function); /// Registers a fallback __newindex handler for the static class table. template Class addStaticNewIndexMetaMethod (Function function); ``` -------------------------------- ### Lua Table Manipulation with Table Proxies Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates accessing and modifying Lua tables using LuaBridge's table proxy syntax. This allows for C++-like assignment to table keys and indices. ```cpp luabridge::LuaRef v (L); v = luabridge::newTable (L); v ["name"] = "John Doe"; // string key, string value v [1] = 200; // integer key, integer value v [2] = luabridge::newTable (L); // integer key, LuaRef value v [3] = v [1]; // assign 200 to integer index 3 v [1] = 100; // v[1] is 100, v[3] is still 200 v [3] = v [2]; // v[2] and v[3] reference the same table v [2] = luabridge::LuaNil (); // Removes the value with key = 2. The table is still referenced by v[3]. ``` -------------------------------- ### Register Vec Class with Property Proxies using Helper Class Source: https://kunitoki.github.io/LuaBridge3/Manual Register a class with members that cannot be directly accessed via pointers-to-members by using a helper class with static get/set functions. This allows accessing members like properties in Lua. ```cpp // Third party declaration, can't be changed struct Vec { float coord [3]; }; struct VecHelper { template static float get (Vec const* vec) { return vec->coord [index]; } template static void set (Vec* vec, float value) { vec->coord [index] = value; } }; luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginClass ("Vec") .addProperty ("x", &VecHelper::get<0>, &VecHelper::set<0>) .addProperty ("y", &VecHelper::get<1>, &VecHelper::set<1>) .addProperty ("z", &VecHelper::get<2>, &VecHelper::set<2>) .endClass () .endNamespace (); ``` -------------------------------- ### Manipulate Lua tables with proxies Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates using LuaRef table proxies to call functions and store values within Lua tables. ```lua t[1](); t[2]("a", "b"); t[2](t[1]); // Call t[3] with the value in t[2] t[4]=t[3](); // Call t[3] and store the result in t[4]. t [t[5]()] = "wow"; // Store "wow" at the key returned by // the call to t[5] t = {} t[1] = function () print ("hello") end t[2] = function (u, v) print (u, v) end t[3] = "foo" ``` -------------------------------- ### Register a constructor proxy with lua_State access Source: https://kunitoki.github.io/LuaBridge3/Manual Include lua_State* as the last parameter in the constructor functor to access the Lua stack during construction. ```cpp luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginClass ("HardToCreate") .addConstructor ([] (void* ptr, lua_State* L) { return new (ptr) HardToCreate (shouldNotSeeMe, lua_checkinteger (L, 2)); }) .endClass () .endNamespace (); ``` -------------------------------- ### Register multiple constructor overloads Source: https://kunitoki.github.io/LuaBridge3/Manual Provide multiple functors to addConstructor to support different argument signatures. ```cpp struct NotExposed; NotExposed* shouldNotSeeMe; struct HardToCreate { HardToCreate (const NotExposed* x, int easy); HardToCreate (const NotExposed* x, int easy, int lessEasy); }; luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginClass ("HardToCreate") .addConstructor ( [&shouldNotSeeMe] (void* ptr, int easy) { return new (ptr) HardToCreate (shouldNotSeeMe, easy); }, [&shouldNotSeeMe] (void* ptr, int easy, int lessEasy) { return new (ptr) HardToCreate (shouldNotSeeMe, easy, lessEasy); }) .endClass () .endNamespace (); ``` -------------------------------- ### Register a custom constructor proxy in C++ Source: https://kunitoki.github.io/LuaBridge3/Manual Use addConstructor with a lambda to handle complex construction logic, such as placement new with non-exposed types. ```cpp struct NotExposed; NotExposed* shouldNotSeeMe; struct HardToCreate { explicit HardToCreate (const NotExposed* x, int easy); }; luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginClass ("HardToCreate") .addConstructor ([&shouldNotSeeMe] (void* ptr, int easy) { return new (ptr) HardToCreate (shouldNotSeeMe, easy); }) .endClass () .endNamespace (); ``` -------------------------------- ### Implicit Type Conversions to C++ Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates implicit C++ conversions from LuaRef to various C++ types. Ensure the LuaRef holds a value convertible to the target type, otherwise a Lua error may occur. ```cpp void passInt (int); void passBool (bool); void passString (std::string); void passObject (A*); LuaRef v (L); //... passInt (v); // implicit conversion to int passBool (v); // implicit conversion to bool passString (v); // implicit conversion to string passObject (v); // must hold a registered LuaBridge class or a // lua_error() will be called. ``` -------------------------------- ### StackTraits Source: https://kunitoki.github.io/LuaBridge3/Manual Utilities for converting C++ values to and from the Lua stack. ```APIDOC ## Stack Traits - Stack ### Description Utilities for converting C++ values to and from the Lua stack. ### Methods - `push(lua_State* L, const T& value)`: Converts the C++ value into the Lua value at the top of the Lua stack. Returns true if the push could be performed. When false is returned, `ec` contains the error code corresponding to the failure. - `get(lua_State* L, int index)`: Converts the Lua value at the index into the C++ value of the type T. - `isInstance(lua_State* L, int index)`: Checks if the Lua value at the index is convertible into the C++ value of the type T. ``` -------------------------------- ### Metamethod Registration Source: https://kunitoki.github.io/LuaBridge3/Manual Functions for registering fallback metamethod handlers for instance and static class tables. ```APIDOC ## Metamethod Registration ### Description Functions for registering fallback metamethod handlers for instance and static class tables. ### Methods #### `addIndexMetaMethod` - **Description**: Registers a fallback `__index` handler for instances (called when a key is not found). - **Template**: `template ` - **Return Type**: `Class` #### `addNewIndexMetaMethod` - **Description**: Registers a fallback `__newindex` handler for instances (called when a key is not found). - **Template**: `template ` - **Return Type**: `Class` #### `addStaticIndexMetaMethod` - **Description**: Registers a fallback `__index` handler for the static class table. - **Template**: `template ` - **Return Type**: `Class` #### `addStaticNewIndexMetaMethod` - **Description**: Registers a fallback `__newindex` handler for the static class table. - **Template**: `template ` - **Return Type**: `Class` ``` -------------------------------- ### Accessing Fallback Properties in Lua Source: https://kunitoki.github.io/LuaBridge3/Manual Lua script demonstrating the behavior of the index fallback defined in the C++ snippet. ```lua propertyOne = flexi.propertyOne assert (propertyOne == 42, "Getting value from LuaBridge exposed property") propertyTwo = flexi.existingProperty assert (propertyTwo == 1337, "Getting value from non exposed LuaBridge property via __index fallback") propertyThree = flexi.nonExistingProperty assert (propertyThree == nil, "Getting value from non exposed LuaBridge property via __index fallback") ``` -------------------------------- ### Registering Class Functions with Lambdas Source: https://kunitoki.github.io/LuaBridge3/Manual Registers class methods using lambdas. Prefixing a lambda with '+' converts it to a function pointer for better performance when no capture is required. ```cpp float y = atan (1.0f) * 4.0f; luabridge::getGlobalNamespace (L) .beginClass ("Vec") .addFunction ("scaleX", +[] (Vec* vec, float v) { vec->coord [0] *= v; }) .addFunction ("scaleY", [y] (Vec* vec, float v) { vec->coord [1] *= v * y; }) .endClass () ``` -------------------------------- ### Static Property Registration Source: https://kunitoki.github.io/LuaBridge3/Manual APIs for registering static properties of a class. ```APIDOC ## Static Property Registration ### Description Registers static properties (getters and setters) for a C++ class. ### Methods #### `addStaticProperty (const char* name, Getter getter)` Registers a static readonly property. #### `addStaticProperty (const char* name, Getter getter, Setter setter)` Registers a static readwrite property. ### Parameters #### Path Parameters - **name** (const char*) - Required - The name of the property. - **getter** (Getter) - Required - The function to get the property value. - **setter** (Setter) - Optional - The function to set the property value. ``` -------------------------------- ### Registering Class Constructors Source: https://kunitoki.github.io/LuaBridge3/Manual Registers constructors by providing their signatures as template parameters. The return type in the signature is ignored. ```cpp struct A { A (); A (std::string_view a); A (std::string_view a, int b); }; struct B { explicit B (const char* s, int nChars); }; luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginClass ("A") .addConstructor () .endClass () .beginClass ("B") .addConstructor () .endClass () .endNamespace (); ``` -------------------------------- ### Static Function Registration Source: https://kunitoki.github.io/LuaBridge3/Manual APIs for registering static functions of a class. ```APIDOC ## Static Function Registration ### Description Registers static functions of a C++ class to be callable from Lua. ### Method #### `addStaticFunction (const char* name, Functions... functions)` Registers one static function or multiple overloads. ``` -------------------------------- ### LuaFunction Constructor and Call Operators Source: https://kunitoki.github.io/LuaBridge3/Manual Constructs a callable Lua function wrapper and provides methods to invoke it. Use callWithHandler for custom error management. ```cpp /// Construct from a LuaRef. explicit LuaFunction (const LuaRef& function); /// Call the function with the given arguments. TypeResult operator() (Args... args) const; /// Call the function — equivalent to operator(). TypeResult call (Args... args) const; /// Call the function with a custom error handler. template TypeResult callWithHandler (F&& errorHandler, Args... args) const; /// Return true if the underlying LuaRef is callable. bool isValid () const; /// Return the underlying LuaRef. const LuaRef& ref () const; ``` -------------------------------- ### Testing Dynamic Property Assignment in Lua Source: https://kunitoki.github.io/LuaBridge3/Manual Lua script verifying that the newindex fallback correctly stores and retrieves dynamic properties. ```lua propertyOne = flexi.propertyOne assert (propertyOne == nil, "Value is not existing") flexi.propertyOne = 1337 propertyOne = flexi.propertyOne assert (propertyOne == 1337, "Value is now present !") ``` -------------------------------- ### Registering Container Constructors Source: https://kunitoki.github.io/LuaBridge3/Manual Uses addConstructorFrom to register class constructors that store objects in a container like std::shared_ptr. ```cpp class C : public std::enable_shared_from_this { C () { } C (int) { } }; luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginClass ("C") .addConstructorFrom, void(), void(int)> () .endClass () .endNamespace () ``` -------------------------------- ### Use a factory-created object in Lua Source: https://kunitoki.github.io/LuaBridge3/Manual Instantiate and garbage collect objects managed by custom factory functions. ```lua a = test.Object () -- Create a new Object using objectFactoryAllocator a = nil -- Remove any reference count collectgarbage ("collect") -- The object is garbage collected using objectFactoryDeallocator ``` -------------------------------- ### Invoke Registered Methods in Lua Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates the use of the colon operator for calling registered class methods in Lua. ```lua local a = A () a.func1 () -- error: func1 expects an object of a registered class a.func1 (a) -- okay, verbose, this how OOP works in Lua a:func1 () -- okay, less verbose, equivalent to the previous ``` -------------------------------- ### Generate Unix Makefiles and Build on Linux Source: https://kunitoki.github.io/LuaBridge3 Use this command to generate Unix Makefiles and build the project on Linux. CMake supports different build types like Debug, Release, and RelWithDebInfo. ```bash git clone --recursive git@github.com:kunitoki/LuaBridge3.git mkdir -p LuaBridge3/build pushd LuaBridge3/build cmake -G "Unix Makefiles" ../ cmake --build . -DCMAKE_BUILD_TYPE=Debug # or cmake --build . -DCMAKE_BUILD_TYPE=Release # or cmake --build . -DCMAKE_BUILD_TYPE=RelWithDebInfo popd ``` -------------------------------- ### Call Wrapped C++ Function from Lua Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates how a C++ function wrapped by LuaBridge can be called directly from Lua, showing the integration between C++ and Lua environments. ```lua print (square (5)) -- 25 ``` -------------------------------- ### C++ Function Signatures for Inheritance Source: https://kunitoki.github.io/LuaBridge3/Manual Demonstrates C++ function signatures that accept a base class type, used to show how LuaBridge handles inheritance with pointers. ```cpp void func5 (B b); void func6 (B* b); ``` -------------------------------- ### Generate XCode Project and Build on MacOS Source: https://kunitoki.github.io/LuaBridge3 This command generates an XCode project for building on MacOS. You can specify the build type using CMAKE_BUILD_TYPE. ```bash git clone --recursive git@github.com:kunitoki/LuaBridge3.git mkdir -p LuaBridge3/build pushd LuaBridge3/build cmake -G Xcode ../ # Generates XCode project build/LuaBridge.xcodeproj cmake --build . -DCMAKE_BUILD_TYPE=Debug # or cmake --build . -DCMAKE_BUILD_TYPE=Release # or cmake --build . -DCMAKE_BUILD_TYPE=RelWithDebInfo popd ``` -------------------------------- ### Evaluate equality with same Source: https://kunitoki.github.io/LuaBridge3/Manual Utility for comparing values in LuaBridge. ```cpp // These all evaluate to true same (1,1); !same (1,2); same ("text", "text"); !same (1, "text"); same (1, 1, 2); // third param ignored ``` -------------------------------- ### LuaFunction Wrapper Source: https://kunitoki.github.io/LuaBridge3/Manual Wrapper class for Lua functions, allowing them to be called from C++. ```APIDOC ## Typed Lua Function Wrapper - LuaFunction ### Description Wrapper class for Lua functions, allowing them to be called from C++. ### Methods - `LuaFunction(const LuaRef& function)`: Construct from a LuaRef. - `operator()(Args... args)`: Call the function with the given arguments. - `call(Args... args)`: Call the function, equivalent to `operator()`. - `callWithHandler(F&& errorHandler, Args... args)`: Call the function with a custom error handler. - `isValid()`: Return true if the underlying LuaRef is callable. - `ref()`: Return the underlying LuaRef. ``` -------------------------------- ### Managing std::shared_ptr with LuaBridge Source: https://kunitoki.github.io/LuaBridge3/Manual This C++ code demonstrates how to integrate `std::shared_ptr` managed objects with LuaBridge, including constructor registration and global variable handling. ```cpp struct A : public std::enable_shared_from_this { A () { } A (int) { } void foo () { } }; luabridge::getGlobalNamespace (L) .beginClass ("A") .addConstructorFrom, void(), void(int)> () .addFunction ("foo", &A::foo) .endClass (); std::shared_ptr a = std::make_shared (1); luabridge::setGlobal (L, a, "a"); std::shared_ptr retrieveA = luabridge::getGlobal> (L, "a"); retrieveA->foo (); ``` -------------------------------- ### Member Function Registration Source: https://kunitoki.github.io/LuaBridge3/Manual APIs for registering member functions of a class. ```APIDOC ## Member Function Registration ### Description Registers member functions of a C++ class to be callable from Lua. ### Method #### `addFunction (const char* name, Functions... functions)` Registers one or multiple overloaded member functions. ``` -------------------------------- ### Namespace Property Registration Source: https://kunitoki.github.io/LuaBridge3/Manual APIs for registering properties within a namespace. ```APIDOC ## Namespace Property Registration ### Description Registers properties within a namespace. ### Methods #### `addProperty (const char* name, Getter getter)` Registers a readonly property. #### `addProperty (const char* name, Getter getter, Setter setter)` Registers a readwrite property. ### Parameters #### Path Parameters - **name** (const char*) - Required - The name of the property. - **getter** (Getter) - Required - The function to get the property value. - **setter** (Setter) - Optional - The function to set the property value. ``` -------------------------------- ### Static Function Fallback Lua Usage Source: https://kunitoki.github.io/LuaBridge3/Manual Verifies that the static function remains accessible when the fallback returns nil. ```lua -- The registered static function is still callable because the fallback returned nil result = MyClass.answer () assert (result == 42) ```