| 20 | struct unrelated { }; |
| 21 | |
| 22 | int main(int, char*[]) { |
| 23 | std::cout << "=== optional with iteration ===" << std::endl; |
| 24 | |
| 25 | sol::state lua; |
| 26 | |
| 27 | // Comment out the new_usertype call |
| 28 | // to prevent derived class "super_thing" |
| 29 | // from being picked up and cast to its base |
| 30 | // class |
| 31 | lua.new_usertype<super_thing>( |
| 32 | "super_thing", sol::base_classes, sol::bases<thing>()); |
| 33 | |
| 34 | // Make a few things |
| 35 | lua["t1"] = thing {}; |
| 36 | lua["t2"] = super_thing {}; |
| 37 | lua["t3"] = unrelated {}; |
| 38 | // And a table |
| 39 | lua["container"] = lua.create_table_with( |
| 40 | 0, thing { 50 }, 1, unrelated {}, 4, super_thing {}); |
| 41 | |
| 42 | |
| 43 | std::vector<std::reference_wrapper<thing>> things; |
| 44 | // Our recursive function |
| 45 | // We use some lambda techniques and pass the function |
| 46 | // itself itself so we can recurse, but a regular function |
| 47 | // would work too! |
| 48 | auto fx = [&things](auto& f, auto& tbl) -> void { |
| 49 | // You can iterate through a table: it has |
| 50 | // begin() and end() |
| 51 | // like standard containers |
| 52 | for (auto key_value_pair : tbl) { |
| 53 | // Note that iterators are extremely frail |
| 54 | // and should not be used outside of |
| 55 | // well-constructed for loops |
| 56 | // that use pre-increment ++, |
| 57 | // or C++ ranged-for loops |
| 58 | const sol::object& key = key_value_pair.first; |
| 59 | const sol::object& value = key_value_pair.second; |
| 60 | sol::type t = value.get_type(); |
| 61 | switch (t) { |
| 62 | case sol::type::table: { |
| 63 | sol::table inner = value.as<sol::table>(); |
| 64 | f(f, inner); |
| 65 | } break; |
| 66 | case sol::type::userdata: { |
| 67 | // This allows us to check if a userdata is |
| 68 | // a specific class type |
| 69 | sol::optional<thing&> maybe_thing |
| 70 | = value.as<sol::optional<thing&>>(); |
| 71 | if (maybe_thing) { |
| 72 | thing& the_thing = maybe_thing.value(); |
| 73 | if (key.is<std::string>()) { |
| 74 | std::cout << "key " |
| 75 | << key.as<std::string>() |
| 76 | << " is a thing -- "; |
| 77 | } |
| 78 | else if (key.is<int>()) { |
| 79 | std::cout << "key " |
nothing calls this directly
no test coverage detected