From 6637f2e1b7f4f81135508e434520ab254e334119 Mon Sep 17 00:00:00 2001 From: Zachary Date: Tue, 29 Mar 2016 13:03:19 -0500 Subject: [PATCH] Added table::get_with_default method There is now a sol::table::get_with_default method that takes 2 arguments, one being the key to search on, the other being the default. If the key does not have a value in the table the default value is returned. --- sol/table_core.hpp | 12 ++++++++++++ tests.cpp | 17 +++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/sol/table_core.hpp b/sol/table_core.hpp index 9b830d4d..6ffc031c 100644 --- a/sol/table_core.hpp +++ b/sol/table_core.hpp @@ -140,6 +140,18 @@ public: return tuple_get( types( ), std::index_sequence_for( ), std::forward_as_tuple(std::forward(keys)...)); } + template + Ret get_with_default(Key key, Ret _default) const { + + sol::optional option = operator[](key); + if( option ){ + return option.value(); + } + else { + return _default; + } + } + template decltype(auto) traverse_get( Keys&&... keys ) const { auto pp = stack::push_pop::value>(*this); diff --git a/tests.cpp b/tests.cpp index 8f95ffc5..159104a9 100644 --- a/tests.cpp +++ b/tests.cpp @@ -505,6 +505,23 @@ TEST_CASE("tables/variables", "Check if tables and variables work as intended") REQUIRE_NOTHROW(lua.script("assert(os.name == \"windows\")")); } +TEST_CASE("simple/get_default", "Test that table::get_default work corretly") { + sol::state lua; + + auto bob_table = lua.create_table("bob"); + int is_set=0; + int is_not_set=0; + bob_table.set("is_set",42); + + is_set = bob_table.get_with_default("is_set",3); + is_not_set = bob_table.get_with_default("is_not_set",22); + + REQUIRE(is_set == 42); + REQUIRE(is_not_set == 22); +} + + + TEST_CASE("tables/create", "Check if creating a table is kosher") { sol::state lua; lua["testtable"] = sol::table::create(lua.lua_state(), 0, 0, "Woof", "Bark", 1, 2, 3, 4);