diff --git a/cheatsheet.md b/cheatsheet.md index eca67f0..25b8469 100644 --- a/cheatsheet.md +++ b/cheatsheet.md @@ -90,6 +90,13 @@ A helper function exists for strongly typed and ChaiScript `Vector` function con chai.add(chaiscript::vector_conversion>()); ``` +A helper function also exists for strongly typed and ChaiScript `Map` function conversion definition: + +``` +chai.add(chaiscript::map_conversion>()); +``` + + This allows you to pass a ChaiScript function to a function requiring `std::vector` ## Adding Objects diff --git a/include/chaiscript/dispatchkit/type_conversions.hpp b/include/chaiscript/dispatchkit/type_conversions.hpp index b5bce8d..2a9a398 100644 --- a/include/chaiscript/dispatchkit/type_conversions.hpp +++ b/include/chaiscript/dispatchkit/type_conversions.hpp @@ -592,6 +592,24 @@ namespace chaiscript return chaiscript::make_shared>(user_type>(), user_type(), func); } + template + Type_Conversion map_conversion() + { + auto func = [](const Boxed_Value &t_bv) -> Boxed_Value { + const std::map &from_map = detail::Cast_Helper &>::cast(t_bv, nullptr); + + To map; + for (const std::pair &p : from_map) { + map.insert(std::make_pair(p.first, detail::Cast_Helper::cast(p.second, nullptr))); + } + + return Boxed_Value(std::move(map)); + }; + + return chaiscript::make_shared>(user_type>(), user_type(), func); + } + + } diff --git a/unittests/compiled_tests.cpp b/unittests/compiled_tests.cpp index 28e7d4c..b27db07 100644 --- a/unittests/compiled_tests.cpp +++ b/unittests/compiled_tests.cpp @@ -872,6 +872,7 @@ struct Returned_Converted_Config }; + TEST_CASE("Return of converted type from script") { chaiscript::ChaiScript chai; @@ -914,3 +915,27 @@ TEST_CASE("Return of converted type from script") } +int get_value_a(const std::map &t_m) +{ + return t_m.at("a"); +} + + +TEST_CASE("Map conversions") +{ + chaiscript::ChaiScript chai; + chai.add(chaiscript::map_conversion>()); + chai.add(chaiscript::fun(&get_value_a), "get_value_a"); + + const auto c = chai.eval(R"( + var m = ["a": 42]; + get_value_a(m); + )"); + + CHECK(c == 42); + +} + + + +