### Sol2 Example Properties Configuration Source: https://github.com/thephd/sol2/blob/develop/examples/CMakeLists.txt Configures properties for a Sol2 example target, linking necessary libraries and setting compile definitions and options. This function is used to standardize the build setup for examples. ```cmake function(sol2_add_example_properties target-name) ttarget_link_libraries(${target-name} PUBLIC Threads::Threads Lua::Lua ${CMAKE_DL_LIBS}) ttarget_compile_definitions(${target-name} PUBLIC SOL_PRINT_ERRORS=1) ttarget_compile_options(${target-name} PRIVATE ${--template-debugging-mode} ${--big-obj} ${--disable-permissive} ${--pedantic} ${--warn-all} ${--warn-pedantic} ${--warn-extra} ${--warn-errors} ${--utf8-literal-encoding} ${--utf8-source-encoding} ${--allow-unknown-warning} ${--allow-unknown-warning-option} ${--allow-noexcept-type} ${--allow-microsoft-cast} ${--allow-unreachable-code} ${--allow-padding-from-alignment} ) ttarget_compile_definitions(${target-name} PRIVATE _CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE) if (SOL2_CI) target_compile_definitions(${target-name} PRIVATE SOL2_CI) endif() if (SOL2_TESTS_EXAMPLES) add_test(NAME ${target-name} COMMAND ${target-name}) endif() if(SOL2_ENABLE_INSTALL) install(TARGETS ${target-name} RUNTIME DESTINATION bin) endif() endfunction() ``` -------------------------------- ### Build All Sol2 Examples Source: https://github.com/thephd/sol2/blob/develop/examples/CMakeLists.txt Iterates through all found Sol2 example source files and creates executables using the 'MAKE_EXAMPLE' function if SOL2_EXAMPLES is enabled. This builds the standard examples. ```cmake if (SOL2_EXAMPLES) foreach(example_source_file ${sol2.examples.sources}) MAKE_EXAMPLE(${example_source_file} "sol2" sol2::sol2) endforeach() endif() ``` -------------------------------- ### Add Examples Subdirectory Source: https://github.com/thephd/sol2/blob/develop/CMakeLists.txt This snippet adds the 'examples' subdirectory to the build when the SOL2_DO_EXAMPLES flag is enabled. This allows examples to be built against the library. ```cmake if (SOL2_DO_EXAMPLES) # NOTE: will also add to tests if TESTS is defined message(STATUS "sol2 adding examples...") add_subdirectory(examples) endif() ``` -------------------------------- ### Build Single-Source Sol2 Examples Source: https://github.com/thephd/sol2/blob/develop/examples/CMakeLists.txt Iterates through all found Sol2 example source files and creates executables using the 'MAKE_EXAMPLE' function if SOL2_EXAMPLES_SINGLE is enabled. This builds examples designed for single-source compilation. ```cmake if (SOL2_EXAMPLES_SINGLE) foreach(example_source_file ${sol2.examples.sources}) MAKE_EXAMPLE(${example_source_file} "sol2.single" sol2::sol2::single) endforeach() endif() ``` -------------------------------- ### Call Lua Function with Arguments Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/stack.md Use this to call a raw C function with Sol2's argument setup abstractions. The 'start' parameter indicates where to begin pulling arguments from the stack. ```cpp template inline int call_lua(lua_State* L, int start, Fx&& fx, FxArgs&&... fxargs); ``` -------------------------------- ### Enable Sol2 Customization Examples Source: https://github.com/thephd/sol2/blob/develop/examples/customization/CMakeLists.txt Conditionally enables the creation of Sol2 customization examples based on CMake variables. If SOL2_EXAMPLES is set, a default customization example is built. If SOL2_EXAMPLES_SINGLE is set, an additional single-file customization example is built. ```cmake if (SOL2_EXAMPLES) MAKE_CUSTOMIZATION_EXAMPLE("" sol2::sol2) endif() if (SOL2_EXAMPLES_SINGLE) MAKE_CUSTOMIZATION_EXAMPLE(".single" sol2::sol2::single) endif() ``` -------------------------------- ### Build Sol2 Luwra Interop Example Source: https://github.com/thephd/sol2/blob/develop/examples/interop/luwra/CMakeLists.txt Conditionally builds the default Sol2 Luwra interop example executable if the SOL2_INTEROP_EXAMPLES variable is set. ```cmake if (SOL2_INTEROP_EXAMPLES) make_luwra_interop_example(sol2::sol2 "") endif() ``` -------------------------------- ### Compile C++ with Sol2 and Lua Source: https://github.com/thephd/sol2/blob/develop/documentation/source/tutorial/getting-started.md Example command to compile a C++ file using g++. Adjust include and library paths according to your system and Lua installation. Ensure C++17 standard is used. ```bash g++ -std=c++17 test.cpp -I"path/to/sol/include" -I"path/to/lua/include" -L"path/to/lua/lib" -llua ``` -------------------------------- ### Glob for Example Source Files Source: https://github.com/thephd/sol2/blob/develop/examples/CMakeLists.txt Uses file(GLOB ...) to find all C++ source files for examples. This command collects source files from 'source/*.cpp', 'source/tutorials/*.cpp', and 'source/tutorials/quick_n_dirty/*.cpp', and 'source/docs/*.cpp'. ```cmake file(GLOB sol2.examples.sources source/*.cpp source/tutorials/*.cpp source/tutorials/quick_n_dirty/*.cpp source/docs/*.cpp) ``` -------------------------------- ### Build Kaguya Interop Examples Source: https://github.com/thephd/sol2/blob/develop/examples/interop/kaguya/CMakeLists.txt Conditionally builds Kaguya interop examples based on CMake variables. It calls the `make_kaguya_interop_example` function to create executables for both default and single-header configurations. ```cmake if (SOL2_INTEROP_EXAMPLES) make_kaguya_interop_example(sol2::sol2 "") endif() if (SOL2_INTEROP_EXAMPLES_SINGLE) make_kaguya_interop_example(sol2::sol2::single ".single") endif() ``` -------------------------------- ### sol::stack::call_lua Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/stack.md Calls a Lua function with C++ abstractions for argument setup. The `start` parameter indicates where to pull arguments from, and `fx` is the function to be called. Extra arguments are passed directly to the function. ```APIDOC ## call_lua ### Description Calls a Lua function with C++ abstractions for argument setup. The `start` parameter indicates where to pull arguments from, and `fx` is the function to be called. Extra arguments are passed directly to the function. ### Signature ```cpp template inline int call_lua(lua_State* L, int start, Fx&& fx, FxArgs&&... fxargs); ``` ``` -------------------------------- ### Build Sol2 Single Luwra Interop Example Source: https://github.com/thephd/sol2/blob/develop/examples/interop/luwra/CMakeLists.txt Conditionally builds the single-threaded Sol2 Luwra interop example executable if the SOL2_INTEROP_EXAMPLES_SINGLE variable is set. ```cmake if (SOL2_INTEROP_EXAMPLES_SINGLE) make_luwra_interop_example(sol2::sol2::single ".single") endif() ``` -------------------------------- ### Add Subdirectory for Require DLL Example Source: https://github.com/thephd/sol2/blob/develop/examples/CMakeLists.txt Conditionally adds the 'require_dll_example' subdirectory to the build if SOL2_DYNAMIC_LOADING_EXAMPLES or SOL2_DYNAMIC_LOADING_EXAMPLES_SINGLE is enabled. This is used for examples demonstrating dynamic loading of Lua modules. ```cmake if (SOL2_DYNAMIC_LOADING_EXAMPLES OR SOL2_DYNAMIC_LOADING_EXAMPLES_SINGLE) # # require_from_dll example # just add the subdirectory add_subdirectory(require_dll_example) endif() ``` -------------------------------- ### Creating and Using sol::environment Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/environment.md Example demonstrating the creation of sol::environment objects and their usage with Lua scripts. ```APIDOC ## Example: Creating and Using sol::environment ### Description This example illustrates how to create custom environments, set variables within them, and execute Lua scripts using these environments. ### Code ```cpp #define SOL_ALL_SAFETIES_ON 1 #include int main(int, char*[]) { sol::state lua; lua.open_libraries(); // Create a new environment with create flag sol::environment my_env(lua, sol::create); my_env["var"] = 50; // Explicitly allow access to 'print' as new environments hide library functions my_env["print"] = lua["print"]; // Create another environment, inheriting from global environment ssol::environment my_other_env( lua, sol::create, lua.globals()); my_other_env["var"] = 443; // Output: 50 lua.script("print(var)", my_env); // Output: 443 lua.script("print(var)", my_other_env); return 0; } ``` ``` -------------------------------- ### Define Kaguya Interop Example Function Source: https://github.com/thephd/sol2/blob/develop/examples/interop/kaguya/CMakeLists.txt This function sets up an executable for Kaguya interop examples, linking against Lua, Kaguya libraries, and the target library. It also configures compiler options and definitions specific to MSVC or other compilers. ```cmake function (make_kaguya_interop_example target_library example_suffix) set(example_name kaguya_interop_example) set(example_name "${example_name}${example_suffix}") add_executable(${example_name} source/kaguya.cpp) target_link_libraries(${example_name} PRIVATE Lua::Lua ${KAGUYA_LIBRARIES} ${target_library} ${CMAKE_DL_LIBS}) if (MSVC) target_compile_options(${example_name} PRIVATE /W1 /std:c++latest /EHsc "$<$:/MDd>" "$<$:/MD>" "$<$:/MD>" "$<$:/MD>") target_compile_definitions(${example_name} PRIVATE UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE) else() target_compile_options(${example_name} PRIVATE -std=c++1z -w -Wno-unknown-warning -Wno-unknown-warning-option) endif() if (SOL2_TESTS_INTEROP_EXAMPLES) add_test(NAME ${example_name} COMMAND ${example_name}) endif() endfunction() ``` -------------------------------- ### Access and Use Usertype Metatable Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/metatable_key.md Demonstrates how to get and use a usertype's metatable in sol2. This example shows retrieving the '__call' metatable function and executing it. ```cpp #define SOL_ALL_SAFETIES_ON 1 #include int main(int, char*[]) { struct bark { int operator()(int x) { return x; } }; sol::state lua; lua.open_libraries(sol::lib::base); lua.new_usertype("bark", sol::meta_function::call_function, &bark::operator()); bark b; lua.set("b", &b); sol::table b_as_table = lua["b"]; sol::table b_metatable = b_as_table[sol::metatable_key]; sol::function b_call = b_metatable["__call"]; sol::function b_as_function = lua["b"]; int result1 = b_as_function(1); // pass 'self' directly to argument int result2 = b_call(b, 1); SOL_ASSERT(result1 == result2); SOL_ASSERT(result1 == 1); SOL_ASSERT(result2 == 1); } ``` -------------------------------- ### Add Subdirectory for Customization Example Source: https://github.com/thephd/sol2/blob/develop/examples/CMakeLists.txt Adds the 'customization' subdirectory to the build. This is used for examples that demonstrate in-depth customization of Sol2's behavior and features. ```cmake # # In-depth customization example add_subdirectory(customization) ``` -------------------------------- ### Build Sol2 Single LuaBridge Interop Example Source: https://github.com/thephd/sol2/blob/develop/examples/interop/LuaBridge/CMakeLists.txt This conditional block calls the `make_luabridge_interop_example` function to build a single-header version of the Sol2 interop example. It is executed only if `SOL2_INTEROP_EXAMPLES_SINGLE` is defined. ```cmake if (SOL2_INTEROP_EXAMPLES_SINGLE) make_luabridge_interop_example(sol2::sol2::single ".single") endif() ``` -------------------------------- ### Build Sol2 LuaBridge Interop Example Source: https://github.com/thephd/sol2/blob/develop/examples/interop/LuaBridge/CMakeLists.txt This conditional block calls the `make_luabridge_interop_example` function to build the main Sol2 interop example. It is executed only if `SOL2_INTEROP_EXAMPLES` is defined. ```cmake if (SOL2_INTEROP_EXAMPLES) make_luabridge_interop_example(sol2::sol2 "") endif() ``` -------------------------------- ### C++ Example with std::unordered_set and std::pair Source: https://github.com/thephd/sol2/blob/develop/documentation/source/containers.md This example demonstrates using std::unordered_set with std::pair as elements in Sol2. It includes a custom hasher for the pair and shows how to expose the set to Lua, print its contents, and iterate over its key-value pairs using a custom :pairs() method. ```cpp #define SOL_ALL_SAFETIES_ON 1 #include #include #include int main() { struct hasher { typedef std::pair argument_type; typedef std::size_t result_type; result_type operator()(const argument_type& p) const { return std::hash()(p.first); } }; using my_set = std::unordered_set< std::pair, hasher>; std::cout << "=== containers with std::pair<> ===" << std::endl; sol::state lua; lua.open_libraries(sol::lib::base); lua.set_function("f", []() { return my_set { { "key1", "value1" }, { "key2", "value2" }, { "key3", "value3" } }; }); lua.safe_script("v = f()"); lua.safe_script("print('v:', v)"); lua.safe_script("print('#v:', #v)"); // note that using my_obj:pairs() is a // way around pairs(my_obj) not working in Lua 5.1/LuaJIT: // try it! lua.safe_script( "for k,v1,v2 in v:pairs() do print(k, v1, v2) end"); std::cout << std::endl; return 0; } ``` -------------------------------- ### Add Subdirectories for Interop Examples Source: https://github.com/thephd/sol2/blob/develop/examples/CMakeLists.txt Conditionally adds subdirectories for various interop examples (kaguya, tolua, LuaBridge, luwra) if SOL2_INTEROP_EXAMPLES or SOL2_INTEROP_EXAMPLES_SINGLE is enabled. This allows building and testing Sol2's interoperability with other Lua bindings. ```cmake if (SOL2_INTEROP_EXAMPLES OR SOL2_INTEROP_EXAMPLES_SINGLE) # # interop examples add_subdirectory(interop/kaguya) add_subdirectory(interop/tolua) add_subdirectory(interop/LuaBridge) add_subdirectory(interop/luwra) endif() ``` -------------------------------- ### Define Customization Example Target Source: https://github.com/thephd/sol2/blob/develop/examples/customization/CMakeLists.txt Defines a CMake function to create a custom Sol2 example executable. It sets up compile options, definitions, and links necessary libraries for both MSVC and other compilers. ```cmake function (MAKE_CUSTOMIZATION_EXAMPLE example_suffix target_sol) set(customization_example_name customization_to_table${example_suffix}) add_executable(${customization_example_name} source/main.cpp source/lua_interop.cpp source/lua_zm_interop.cpp) set_target_properties(${customization_example_name} PROPERTIES OUTPUT_NAME "${customization_example_name}" EXPORT_NAME sol2::${customization_example_name}) if (MSVC) target_compile_options(${customization_example_name} PRIVATE /std:c++latest /EHsc "$<$:/MDd>" "$<$:/MD>" "$<$:/MD>" "$<$:/MD>") target_compile_definitions(${customization_example_name} PRIVATE UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE) else() target_compile_options(${customization_example_name} PRIVATE -std=c++1z -ftemplate-backtrace-limit=0 -Wno-unknown-warning -Wno-unknown-warning-option -Wall -Wpedantic -Werror -pedantic -pedantic-errors -Wno-noexcept-type) endif() target_link_libraries(${customization_example_name} PRIVATE Threads::Threads ${target_sol} Lua::Lua) target_include_directories(${customization_example_name} PRIVATE include) endfunction() ``` -------------------------------- ### Dynamic Object Example in Sol2 Source: https://github.com/thephd/sol2/blob/develop/documentation/source/usertypes.md Illustrates the creation of a fully dynamic object using Sol2. This approach is beneficial when the structure or members of an object are not known at compile time. ```cpp struct DynamicObject { sol::table data; }; sol::usertype dynamic_object_type(sol.lua_state(), "DynamicObject", sol::constructors() ); dynamic_object_type.set("data", &DynamicObject::data); ``` -------------------------------- ### Basic Overload Usage Example Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/overload.md Demonstrates how to use `sol::overload` to bind multiple functions (including a lambda) to a single name in Lua. This example shows binding `ultra_bark`, a lambda, and implicitly a member function `pup::bark`. ```cpp #define SOL_ALL_SAFETIES_ON 1 #include #include struct pup { int barks = 0; void bark() { ++barks; // bark! } bool is_cute() const { return true; } }; void ultra_bark(pup& p, int barks) { for (; barks-- > 0;) p.bark(); } void picky_bark(pup& p, std::string s) { if (s == "bark") p.bark(); } ``` ```cpp int main() { std::cout << "=== overloading with members ===" << std::endl; sol::state lua; lua.open_libraries(sol::lib::base); lua.set_function("bark", sol::overload(ultra_bark, []() { return "the bark from nowhere"; })); lua.new_usertype("pup", // regular function "is_cute", &pup::is_cute, // overloaded function "bark", ``` ```lua barker = pup.new() print(barker:is_cute()) barker:bark() -- calls member function pup::bark barker:bark("meow") -- picky_bark, no bark barker:bark("bark") -- picky_bark, bark bark(barker, 20) -- calls ultra_bark print(bark()) -- calls lambda which returns that string ``` -------------------------------- ### Example: Check for Lua Nil Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/object.md Demonstrates how to compare a sol::object against sol::lua_nil to determine if it holds a value. ```cpp if (myobj == sol::lua_nil) { // doesn't have anything... } ``` -------------------------------- ### Get or Create Methods Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/proxy.md Methods to retrieve a value if it exists, or create and return a new value if it does not. ```APIDOC ## get_or_create() ### Description Gets the value associated with the keys if it exists. If it does not, it will set it with a default-constructed value of type T and return the result. ### Method `get_or_create()` ### Parameters - **T** (type) - The target C++ type to create if the value does not exist. ## get_or_create(Otherwise&& other) ### Description Gets the value associated with the keys if it exists. If it does not, it will set it with the provided `other` value and return the result. ### Method `get_or_create(Otherwise&& other)` ### Parameters - **T** (type) - The target C++ type to create if the value does not exist. - **Otherwise** (type) - The type of the value to set if it does not exist. - **other** (type) - The value to set if the key does not exist. ``` -------------------------------- ### Example Usage of sol::c_call for Function Binding Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/c_call.md Demonstrates various ways to use sol::c_call to bind C++ functions, including overloaded functions and member functions, to a Lua state. This example requires including the sol2 header and defining SOL_ALL_SAFETIES_ON. ```cpp #define SOL_ALL_SAFETIES_ON 1 #include int f1(int) { return 32; } int f2(int, int) { return 1; } struct fer { double f3(int, int) { return 2.5; } }; int main() { sol::state lua; // overloaded function f lua.set("f", sol::c_call, sol::wrap, sol::wrap>); // singly-wrapped function lua.set("g", sol::c_call>); // without the 'sol::wrap' boilerplate lua.set("h", sol::c_call); // object used for the 'fer' member function call lua.set("obj", fer()); // call them like any other bound function lua.script("r1 = f(1)"); lua.script("r2 = f(1, 2)"); lua.script("r3 = f(obj, 1, 2)"); lua.script("r4 = g(1)"); lua.script("r5 = h(1, 2)"); // get the results and see // if it worked out int r1 = lua["r1"]; SOL_ASSERT(r1 == 32); int r2 = lua["r2"]; SOL_ASSERT(r2 == 1); double r3 = lua["r3"]; SOL_ASSERT(r3 == 2.5); int r4 = lua["r4"]; SOL_ASSERT(r4 == 32); int r5 = lua["r5"]; SOL_ASSERT(r5 == 1); return 0; } ``` -------------------------------- ### Lua Script for Example Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/proxy.md This Lua script defines a nested table 'bark' with a key 'woof' and a string value. ```lua woof = { [2] = "arf!" } } ``` -------------------------------- ### Complete C++ Example with std::vector Source: https://github.com/thephd/sol2/blob/develop/documentation/source/containers.md This example shows a full integration of std::vector with Lua. It demonstrates passing a vector to Lua, calling a Lua function with the vector, modifying the vector from C++, and using Lua's member functions to add elements, clear the vector, and observe the changes. ```cpp #define SOL_ALL_SAFETIES_ON 1 #include #include #include int main(int, char**) { std::cout << "=== containers ===" << std::endl; sol::state lua; lua.open_libraries(); lua.script(R"( function f (x) print(\"container has:\") for k=1,#x do v = x[k] print(\" \", k, v) end print() end )") // Have the function we // just defined in Lua sol::function f = lua["f"]; // Set a global variable called // "arr" to be a vector of 5 lements lua["arr"] = std::vector { 2, 4, 6, 8, 10 }; // Call it, see 5 elements // printed out f(lua["arr"]); // Mess with it in C++ // Containers are stored as userdata, unless you // use `sol::as_table()` and `sol::as_table_t`. std::vector& reference_to_arr = lua["arr"]; reference_to_arr.push_back(12); // Call it, see *6* elements // printed out f(lua["arr"]); lua.script(R"( arr:add(28) )") // Call it, see *7* elements // printed out f(lua["arr"]); lua.script(R"( arr:clear() )") // Now it's empty f(lua["arr"]); std::cout << std::endl; return 0; } ``` -------------------------------- ### Setting and Getting Environment Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/environment.md Functions to set a sol::environment for a target or retrieve the environment of a target. ```APIDOC ## Environment Management Functions ### `template bool set_environment( const environment& env, const T& target );` Sets the provided `environment` as the execution environment for the given `target`. ### `template basic_environment get_environment( const T& target );` Retrieves the execution environment associated with the given `target`. ``` -------------------------------- ### Open a Sol2 State and Run Basic Script Source: https://github.com/thephd/sol2/blob/develop/documentation/source/tutorial/all-the-things.md Demonstrates how to initialize a sol::state, open standard Lua libraries, and execute a simple Lua print statement from C++. ```cpp #define SOL_ALL_SAFETIES_ON 1 #include #include int main(int, char*[]) { std::cout << "=== opening a state ===" << std::endl; sol::state lua; // open some common libraries lua.open_libraries(sol::lib::base, sol::lib::package); lua.script("print('bark bark bark!')"); std::cout << std::endl; return 0; } ``` -------------------------------- ### Basic Sol2 C++ Example Source: https://github.com/thephd/sol2/blob/develop/documentation/source/tutorial/getting-started.md A minimal C++ program demonstrating the initialization of Sol2, opening the base Lua library, and executing a simple Lua script. Ensure your compiler is set to C++17 or later. ```cpp #define SOL_ALL_SAFETIES_ON 1 #include // or #include "sol.hpp", whichever suits your needs int main(int argc, char* argv[]) { sol::state lua; lua.open_libraries(sol::lib::base); lua.script("print('bark bark bark!')"); return 0; } ``` -------------------------------- ### Specializing unique_usertype_traits for boost::shared_ptr Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/unique_usertype_traits.md Example specialization of `unique_usertype_traits` for `boost::shared_ptr`. This allows Sol2 to correctly handle `boost::shared_ptr` objects, including their ref-counting semantics. The `is_null` function determines if a `nil` value should be pushed to Lua, and `get` provides a raw pointer to the managed object. ```cpp namespace sol { template struct unique_usertype_traits> { typedef T type; typedef boost::shared_ptr actual_type; static const bool value = true; static bool is_null(const actual_type& ptr) { return ptr == nullptr; } static type* get (const actual_type& ptr) { return ptr.get(); } }; } ``` -------------------------------- ### Creating Lua Tables with Sol2 Source: https://github.com/thephd/sol2/blob/develop/documentation/source/tutorial/all-the-things.md Shows how to create simple and nested Lua tables using `create_table_with` and `create_named_table`. Demonstrates referencing existing Sol2 objects within new tables. ```cpp #define SOL_ALL_SAFETIES_ON 1 #include int main(int, char*[]) { sol::state lua; lua.open_libraries(sol::lib::base); lua["abc_sol2"] = lua.create_table_with(0, 24); sol::table inner_table = lua.create_table_with("bark", 50, // can reference other existing stuff too "woof", lua["abc_sol2"]); lua.create_named_table("def_sol2", "ghi", inner_table); std::string code = R"( abc = { [0] = 24 } def = { ghi = { ``` ```lua bark = 50, woof = abc } } ) ``` ```cpp lua.script(code); lua.script(R"( assert(abc_sol2[0] == abc[0]) assert(def_sol2.ghi.bark == def.ghi.bark) )"); return 0; } ``` -------------------------------- ### Creating and Using Custom Environments Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/environment.md Demonstrates creating isolated Lua environments with custom variables and controlling access to global functions like 'print'. ```cpp #define SOL_ALL_SAFETIES_ON 1 #include int main(int, char*[]) { sol::state lua; lua.open_libraries(); sol::environment my_env(lua, sol::create); // set value, and we need to explicitly allow for // access to "print", since a new environment hides // everything that's not defined inside of it // NOTE: hiding also hides library functions (!!) // BE WARNED my_env["var"] = 50; my_env["print"] = lua["print"]; sol::environment my_other_env( lua, sol::create, lua.globals()); // do not need to explicitly allow access to "print", // since we used the "Set a fallback" version // of the sol::environment constructor my_other_env["var"] = 443; // output: 50 lua.script("print(var)", my_env); // output: 443 lua.script("print(var)", my_other_env); return 0; } ``` -------------------------------- ### Conditional Build of ToLua Interop Examples Source: https://github.com/thephd/sol2/blob/develop/examples/interop/tolua/CMakeLists.txt This section of the CMake script conditionally builds the ToLua interop examples. It checks if the `SOL2_INTEROP_EXAMPLES` or `SOL2_INTEROP_EXAMPLES_SINGLE` variables are defined to determine whether to create the default or single-suffix example targets. ```cmake MESSAGE(STATUS ${SOL2_LUA_VERSION}) if (SOL2_INTEROP_EXAMPLES) make_tolua_interop_example(sol2::sol2 "") endif() if (SOL2_INTEROP_EXAMPLES_SINGLE) make_tolua_interop_example(sol2::sol2::single ".single") endif() ``` -------------------------------- ### Stack Top and Field Access Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/stack.md Functions to get the number of values on the stack and to get or set fields within Lua tables. ```APIDOC ## top ### Description Returns the number of values currently on the Lua stack. ### Method Signature ```cpp int top( lua_State* L ) ``` ## set_field ### Description Sets the field referenced by the key `k` to the given value `v`. Pushes the key and value onto the stack and performs `lua_setfield`. ### Method Signatures ```cpp template void set_field( lua_State* L, Key&& k, Value&& v ) template void set_field( lua_State* L, Key&& k, Value&& v, int objectindex) ``` ## get_field ### Description Gets the field referenced by the key `k`. Pushes the key onto the stack and performs `lua_getfield`. Leaves the retrieved value on the stack. ### Method Signatures ```cpp template void get_field( lua_State* L, Key&& k [, int objectindex] ) ``` ## probe_get_field ### Description Safely gets the field referenced by the key `k`, performing `lua_getfield` and stopping traversal if the value cannot be indexed into. Returns probing information. ### Method Signature ```cpp template probe probe_get_field( lua_State* L, Key&& k [, int objectindex] ) ``` ``` -------------------------------- ### Make Example Executable Function Source: https://github.com/thephd/sol2/blob/develop/examples/CMakeLists.txt Defines a CMake function 'MAKE_EXAMPLE' to create an executable for a given source file. It handles naming, path resolution, and linking against the specified Sol2 target. ```cmake function (MAKE_EXAMPLE example_source_file example_prefix target_sol) get_filename_component(example_name ${example_source_file} NAME_WE) file(RELATIVE_PATH example_source_file_relative ${CMAKE_SOURCE_DIR} ${example_source_file}) get_filename_component(example_output_relative_dir ${example_source_file_relative} DIRECTORY) file(TO_CMAKE_PATH "${example_output_relative_dir}" example_output_relative_dir_name) STRING(REGEX REPLACE "/" "." example_output_relative_dir_name "${example_output_relative_dir_name}") if (example_output_relative_dir_name STREQUAL "") set(example_output_name ${example_name}) set(example_name "${example_prefix}.${example_name}") else() set(example_output_name ${example_output_relative_dir_name}.${example_name}) set(example_name "${example_prefix}.${example_output_relative_dir_name}.${example_name}") endif() add_executable(${example_name} ${example_source_file}) sol2_add_example_properties(${example_name}) target_link_libraries(${example_name} PRIVATE ${target_sol}) endfunction(MAKE_EXAMPLE) ``` -------------------------------- ### Raw Get Value from Table Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/table.md Retrieves items from a table without invoking metamethods. Similar to `get`, but operates directly on the table's data. ```cpp template decltype(auto) raw_get(Keys&&... keys) const; template decltype(auto) traverse_raw_get(Keys&&... keys) const; template decltype(auto) raw_get_or(Key&& key, T&& otherwise) const; template decltype(auto) raw_get_or(Key&& key, D&& otherwise) const; ``` -------------------------------- ### Define `make_require_from_dll_example` Function Source: https://github.com/thephd/sol2/blob/develop/examples/require_dll_example/CMakeLists.txt This function defines CMake targets for a shared library and an executable. It sets up include directories, compile definitions, and links necessary libraries like Lua and platform-specific dynamic loading libraries. ```cmake function(make_require_from_dll_example target_lib example_lib_name_suffix) # define sources set(my_object_sources source/my_object.cpp) set(require_from_dll_sources source/require_from_dll.cpp) # define names set(example_lib_name my_object) set(example_name require_from_dll) set(example_lib_name "${example_lib_name}${example_lib_name_suffix}") set(example_name "${example_name}${example_lib_name_suffix}") # add library target my_object for the require_from_dll program add_library(${example_lib_name} SHARED ${my_object_sources}) set_target_properties(${example_lib_name} PROPERTIES PREFIX "") target_include_directories(${example_lib_name} PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") target_compile_definitions(${example_lib_name} PUBLIC MY_OBJECT_DLL PRIVATE MY_OBJECT_BUILD) target_link_libraries(${example_lib_name} PUBLIC ${target_lib} Lua::Lua ${CMAKE_DL_LIBS}) target_include_directories(${example_lib_name} PUBLIC "${LUA_INCLUDE_DIRS}") if (MSVC) target_compile_options(${example_lib_name} PRIVATE /std:c++latest /EHsc "$<$:/MDd>" "$<$:/MD>" "$<$:/MD>" "$<$:/MD>") target_compile_definitions(${example_lib_name} PRIVATE UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE) else() target_compile_options(${example_lib_name} PRIVATE -std=c++1z -Wno-unknown-warning -Wno-unknown-warning-option -Wall -Wextra -Wpedantic -pedantic -pedantic-errors -Wno-noexcept-type) if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") # For another day, when C++ is not so crap # and we have time to audit the entire lib # for all uses of `detail::swallow`... #target_compile_options(${test_target_name} # PRIVATE -Wcomma) endif() if (IS_X86) target_compile_options(${example_lib_name} BEFORE PRIVATE -m32) endif() endif() # add executable target that represents require_from_dll program add_executable(${example_name} ${require_from_dll_sources}) target_link_libraries(${example_name} PRIVATE my_object Lua::Lua ${target_lib} ${CMAKE_DL_LIBS}) target_include_directories(${example_name} PRIVATE "${LUA_INCLUDE_DIRS}") if (MSVC) target_compile_options(${example_name} PRIVATE /std:c++latest /EHsc "$<$:/MDd>" "$<$:/MD>" "$<$:/MD>" "$<$:/MD>") target_compile_definitions(${example_name} PRIVATE UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE) else() target_compile_options(${example_name} PRIVATE -std=c++1z -Wno-unknown-warning -Wno-unknown-warning-option -Wall -Wextra -Wpedantic -pedantic -pedantic-errors -Wno-noexcept-type) if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") # For another day, when C++ is not so crap # and we have time to audit the entire lib # for all uses of `detail::swallow`... #target_compile_options(${test_target_name} # PRIVATE -Wcomma) endif() endif() if (SOL2_TESTS_DYNAMIC_LOADING_EXAMPLES) get_target_property(example_working_dir ${example_name} RUNTIME_OUTPUT_DIRECTORY) add_test(NAME ${example_name} COMMAND ${example_name} WORKING_DIRECTORY "${example_working_dir}") endif() endfunction() ``` -------------------------------- ### Basic Lua Scripting with C++ Functions Source: https://github.com/thephd/sol2/blob/develop/README.md Demonstrates setting a C++ function in Lua and calling it from a Lua script. Ensure sol2 headers are included. ```cpp #include #include int main() { sol::state lua; int x = 0; lua.set_function("beep", [&x]{ ++x; }); lua.script("beep()"); assert(x == 1); } ``` -------------------------------- ### Define Luwra Interop Example Function Source: https://github.com/thephd/sol2/blob/develop/examples/interop/luwra/CMakeLists.txt Defines a CMake function to create an executable for Luwra interop examples. It links against Lua, Luwra libraries, and the Sol2 library, with platform-specific compile options and definitions. ```cmake function (make_luwra_interop_example target_library example_suffix) set(example_name luwra_interop_example) set(example_name "${example_name}${example_suffix}") add_executable(${example_name} source/luwra.cpp) target_link_libraries(${example_name} PRIVATE Lua::Lua ${LUWRA_LIBRARIES} ${target_library} ${CMAKE_DL_LIBS}) if (MSVC) target_compile_options(${example_name} PRIVATE /std:c++latest /EHsc "$<$:/MDd>" "$<$:/MD>" "$<$:/MD>" "$<$:/MD>") target_compile_definitions(${example_name} PRIVATE /W1 UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE) else() target_compile_options(${example_name} PRIVATE -std=c++1z -w -Wno-unknown-warning -Wno-unknown-warning-option) endif() if (SOL2_TESTS_INTEROP_EXAMPLES) add_test(NAME ${example_name} COMMAND ${example_name}) endif() endfunction() ``` -------------------------------- ### Get Value from Table Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/table.md Retrieves items from a table. `get` can retrieve multiple values into a std::tuple. `traverse_get` retrieves a single value through nested keys. Use `get_or` for a default value if a key does not exist. ```cpp template decltype(auto) get(Keys&&... keys) const; template decltype(auto) traverse_get(Keys&&... keys) const; template decltype(auto) get_or(Key&& key, T&& otherwise) const; template decltype(auto) get_or(Key&& key, D&& otherwise) const; ``` -------------------------------- ### Writing and Reading Lua Variables and Tables Source: https://github.com/thephd/sol2/blob/develop/documentation/source/tutorial/variables.md Demonstrates setting basic variables (numbers) and creating Lua tables with various key-value pairs in the global Lua state from C++. It also shows how to execute Lua scripts that access these variables and table elements. ```cpp #define SOL_ALL_SAFETIES_ON 1 #include #include int main() { sol::state lua; // open those basic lua libraries // again, for print() and other basic utilities lua.open_libraries(sol::lib::base); // value in the global table lua["bark"] = 50; // a table being created in the global table lua["some_table"] = lua.create_table_with("key0", 24, "key1", 25, lua["bark"], "the key is 50 and this string is its value!"); // Run a plain ol' string of lua code // Note you can interact with things set through sol in C++ // with lua! Using a "Raw String Literal" to have multi-line // goodness: // http://en.cppreference.com/w/cpp/language/string_literal lua.script(R"( print(some_table[50]) print(some_table["key0"]) print(some_table["key1"]) -- a lua comment: access a global in a lua script with the _G table print(_G["bark"]) )"); return 0; } ``` -------------------------------- ### Open Multiple Lua Libraries Source: https://github.com/thephd/sol2/blob/develop/documentation/source/tutorial/getting-started.md This C++ snippet shows how to initialize Sol2 and open several standard Lua libraries, including base, coroutine, string, and io, before executing a Lua script. ```cpp #define SOL_ALL_SAFETIES_ON 1 #include int main(int argc, char* argv[]) { sol::state lua; lua.open_libraries(sol::lib::base, sol::lib::coroutine, sol::lib::string, sol::lib::io); lua.script("print('bark bark bark!')"); return 0; } ``` -------------------------------- ### Get Value from Lua Stack Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/stack.md Retrieves a value from the Lua stack at a specified index. The return type depends on the template parameter T. It attempts to get the value as T, and then as T with const/reference qualifiers removed if the first attempt fails. ```cpp template auto get( lua_State* L, int index = -1 ) template auto get( lua_State *L, int index, record& tracking ) ``` -------------------------------- ### Demonstrating sol::protect with Usertypes Source: https://github.com/thephd/sol2/blob/develop/documentation/source/api/protect.md This example shows how to use `sol::protect` with a usertype to ensure that a member function call, when passed incorrect arguments, fails gracefully via `pcall`. This requires `SOL_ALL_SAFETIES_ON` to be defined. ```cpp #define SOL_ALL_SAFETIES_ON 1 #include int main(int, char*[]) { struct protect_me { int gen(int x) { return x; } }; sol::state lua; lua.open_libraries(sol::lib::base); lua.new_usertype( "protect_me", "gen", sol::protect(&protect_me::gen)); lua.script(R"__( pm = protect_me.new() value = pcall(pm.gen,"wrong argument") )__"); bool value = lua["value"]; SOL_ASSERT(!value); return 0; } ``` -------------------------------- ### Define LuaBridge Interop Example Function Source: https://github.com/thephd/sol2/blob/develop/examples/interop/LuaBridge/CMakeLists.txt This function defines a CMake target for a LuaBridge interop example. It links against Lua, LuaBridge libraries, and the specified target library. It also includes platform-specific compile options and definitions for MSVC and other compilers. ```cmake function (make_luabridge_interop_example target_library example_suffix) set(example_name luabridge_interop_example) set(example_name "${example_name}${example_suffix}") add_executable(${example_name} source/LuaBridge.cpp) target_link_libraries(${example_name} PRIVATE Lua::Lua ${LUABRIDGE_LIBRARIES} ${target_library} ${CMAKE_DL_LIBS}) if (MSVC) target_compile_options(${example_name} PRIVATE /std:c++latest /EHsc "$<$:/MDd>" "$<$:/MD>" "$<$:/MD>" "$<$:/MD>") target_compile_definitions(${example_name} PRIVATE /W1 UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE) else() target_compile_options(${example_name} PRIVATE -std=c++1z -w -Wno-unknown-warning -Wno-unknown-warning-option) endif() if (SOL2_TESTS_INTEROP_EXAMPLES) add_test(NAME ${example_name} COMMAND ${example_name}) endif() endfunction() ```