Skip to content

Commit

Permalink
Formula engine: Substring function now accepts negative size
Browse files Browse the repository at this point in the history
This results in counting backwards from the given offset.
Size of 1 and -1 have the same effect.
  • Loading branch information
CelticMinstrel committed Mar 18, 2016
1 parent 159dbcf commit 1cf9f61
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 18 deletions.
18 changes: 3 additions & 15 deletions src/formula_function.cpp
Expand Up @@ -395,31 +395,19 @@ class substring_function
if(offset < 0) {
offset += result.size();
if(offset < 0) {
WRN_SF << "[substring] Offset '"
<< args()[1]->evaluate(variables, fdb).as_int()
<< "' results in a negative start in string '"
<< result
<< "' and is reset at the beginning of the string.\n";

offset = 0;
}
} else {
if(static_cast<size_t>(offset) >= result.size()) {
WRN_SF << "[substring] Offset '" << offset
<< "' is larger than the size of '" << result
<< "' and results in an empty string.\n";

return variant(std::string());
}
}

if(args().size() > 2) {
const int size = args()[2]->evaluate(variables, fdb).as_int();
int size = args()[2]->evaluate(variables, fdb).as_int();
if(size < 0) {
ERR_SF << "[substring] Size is negative an "
<< "empty string is returned.\n";

return variant(std::string());
size = -size;
offset = std::max(0, offset - size + 1);
}
return variant(result.substr(offset, size));
} else {
Expand Down
14 changes: 11 additions & 3 deletions src/tests/test_formula_function.cpp
Expand Up @@ -73,12 +73,10 @@ BOOST_AUTO_TEST_CASE(test_formula_function_substring)
.evaluate().as_string()
, "");

lg::set_log_domain_severity("scripting/formula", lg::err.get_severity() - 1); // Don't log anything

BOOST_CHECK_EQUAL(
game_logic::formula("substring('hello world', 0, -1)")
.evaluate().as_string()
, "");
, "h");

lg::set_log_domain_severity("scripting/formula", lg::debug);

Expand All @@ -97,6 +95,16 @@ BOOST_AUTO_TEST_CASE(test_formula_function_substring)
.evaluate().as_string()
, "ello worl");

BOOST_CHECK_EQUAL(
game_logic::formula("substring('hello world', -1, -5)")
.evaluate().as_string()
, "world");

BOOST_CHECK_EQUAL(
game_logic::formula("substring('hello world', 4, -5)")
.evaluate().as_string()
, "hello");

}

BOOST_AUTO_TEST_CASE(test_formula_function_length)
Expand Down

0 comments on commit 1cf9f61

Please sign in to comment.