diff options
author | Andy <drumsetmonkey@gmail.com> | 2019-08-29 13:07:45 -0400 |
---|---|---|
committer | Andy <drumsetmonkey@gmail.com> | 2019-08-29 13:07:45 -0400 |
commit | 4ac4b280abf2ffa28caa5a532353115a3033444f (patch) | |
tree | 2a13d658bb454360b2faf401244bb0321d3460d4 /lib/sol2/examples/source/dynamic_object.cpp | |
parent | e9758416b18b27a65337c28d9641afc0ee89b34b (diff) | |
parent | 7a46fa2dd3dad3f038bf8e7339bc67abca428ae6 (diff) |
Started creating scripting library/namespace and added sol2 for interfacing
Diffstat (limited to 'lib/sol2/examples/source/dynamic_object.cpp')
-rw-r--r-- | lib/sol2/examples/source/dynamic_object.cpp | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/lib/sol2/examples/source/dynamic_object.cpp b/lib/sol2/examples/source/dynamic_object.cpp new file mode 100644 index 0000000..3d04da6 --- /dev/null +++ b/lib/sol2/examples/source/dynamic_object.cpp @@ -0,0 +1,84 @@ +#define SOL_ALL_SAFETIES_ON 1 +#include <sol/sol.hpp> + +#include <iostream> +#include "assert.hpp" + +// use as-is, +// add as a member of your class, +// or derive from it and bind it appropriately +struct dynamic_object { + std::unordered_map<std::string, sol::object> entries; + + void dynamic_set(std::string key, sol::stack_object value) { + auto it = entries.find(key); + if (it == entries.cend()) { + entries.insert(it, { std::move(key), std::move(value) }); + } + else { + std::pair<const std::string, sol::object>& kvp = *it; + sol::object& entry = kvp.second; + entry = sol::object(std::move(value)); + } + } + + sol::object dynamic_get(std::string key) { + auto it = entries.find(key); + if (it == entries.cend()) { + return sol::lua_nil; + } + return it->second; + } +}; + + +int main() { + std::cout << "=== dynamic_object ===" << std::endl; + + sol::state lua; + lua.open_libraries(sol::lib::base); + + lua.new_usertype<dynamic_object>("dynamic_object", + sol::meta_function::index, &dynamic_object::dynamic_get, + sol::meta_function::new_index, &dynamic_object::dynamic_set, + sol::meta_function::length, [](dynamic_object& d) { + return d.entries.size(); + } + ); + + lua.safe_script(R"( +d1 = dynamic_object.new() +d2 = dynamic_object.new() + +print(#d1) -- length operator +print(#d2) + +function d2:run(lim) + local r = 0 + for i=0,lim do + r = r + i + end + if (r % 2) == 1 then + print("odd") + end + return r +end + +-- only added an entry to d2 +print(#d1) +print(#d2) + +-- only works on d2 +local value = d2:run(5) +assert(value == 15) +)"); + + // does not work on d1: 'run' wasn't added to d1, only d2 + auto script_result = lua.safe_script("local value = d1:run(5)", sol::script_pass_on_error); + c_assert(!script_result.valid()); + sol::error err = script_result; + std::cout << "received expected error: " << err.what() << std::endl; + std::cout << std::endl; + + return 0; +}
\ No newline at end of file |