Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions include/behaviortree_cpp/scripting/operators.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include "behaviortree_cpp/scripting/script_parser.hpp"

#include <cmath>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
Expand Down Expand Up @@ -407,11 +408,32 @@ struct ExprComparison : ExprBase
}
else if(lhs_v.isString() && rhs_v.isString())
{
auto lv = lhs_v.cast<SimpleString>();
auto rv = rhs_v.cast<SimpleString>();
if(!SwitchImpl(lv, rv, ops[i]))
// Try numeric comparison when both strings are parseable as numbers.
// This handles values set via blackboard->set(key, "42"). Issue #974.
auto ls = lhs_v.cast<std::string>();
auto rs = rhs_v.cast<std::string>();
char* lend = nullptr;
char* rend = nullptr;
double ld = std::strtod(ls.c_str(), &lend);
double rd = std::strtod(rs.c_str(), &rend);
bool l_numeric = (lend == ls.c_str() + ls.size()) && !ls.empty();
bool r_numeric = (rend == rs.c_str() + rs.size()) && !rs.empty();

if(l_numeric && r_numeric)
{
return False;
if(!SwitchImpl(ld, rd, ops[i]))
{
return False;
}
}
else
{
auto lv = lhs_v.cast<SimpleString>();
auto rv = rhs_v.cast<SimpleString>();
if(!SwitchImpl(lv, rv, ops[i]))
{
return False;
}
}
}
else if(lhs_v.isString() && rhs_v.isNumber())
Expand Down
31 changes: 31 additions & 0 deletions tests/gtest_blackboard.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -745,3 +745,34 @@ TEST(BlackboardTest, SetBlackboard_WithPortRemapping)
// Tick till the end with no crashes
ASSERT_NO_THROW(tree.tickWhileRunning(););
}

// Issue #974: blackboard->set(key, "42") stores a string.
// When two string-valued blackboard entries are compared in a script,
// numeric comparison should be used if both strings are parseable as numbers.
// "9" < "10" is false lexicographically but true numerically.
TEST(BlackboardTest, StringSetNumericScriptComparison_Issue974)
{
auto bb = Blackboard::create();
bb->set("a", std::string("9"));
bb->set("b", std::string("10"));

BehaviorTreeFactory factory;

std::string xml_txt = R"(
<root BTCPP_format="4" >
<BehaviorTree ID="Main">
<Sequence>
<Script code=" result := false "/>
<Script code=" result := (a < b) "/>
<AlwaysSuccess _successIf="result"/>
</Sequence>
</BehaviorTree>
</root>)";

auto tree = factory.createTreeFromText(xml_txt, bb);
auto status = tree.tickWhileRunning();

ASSERT_EQ(status, NodeStatus::SUCCESS);
// 9 < 10 is true numerically, even though "9" > "10" lexicographically
ASSERT_TRUE(bb->get<bool>("result"));
}
Loading