Skip to content

Commit

Permalink
fix string multiplication
Browse files Browse the repository at this point in the history
  • Loading branch information
Prevter committed Nov 1, 2024
1 parent 828e780 commit e1997ce
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/value.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,19 @@ namespace rift {

// If either value is a string, repeat it n times, where n is the second value.
if (isString() || other.isString()) {
// make sure only one of them is a string
if (isString() && other.isString()) {
return string("<error: multiplication of strings>");
}

// figure out which one is string
const Value &str = isString() ? *this : other;
const Value &num = isString() ? other : *this;

// repeat the string n times
std::string result;
auto count = other.isInteger() ? other.toInteger() : static_cast<int>(other.toFloat());
for (int i = 0; i < count; ++i) {
result += isString() ? getString() : other.getString();
for (int i = 0; i < num.toInteger(); ++i) {
result += str.toString();
}
return string(std::move(result));
}
Expand Down
1 change: 1 addition & 0 deletions test/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ int main() {
RIFT_TEST_CASE("{$'string interpolation: {2 + 2}'}", "string interpolation: 4");
RIFT_TEST_CASE("{float('3.14')} {int('100')} {str(3.1415926)} {int('ABC')}", "3.14 100 3.14 NaN");
RIFT_TEST_CASE("{precision(float('3.149268') * 1.5, 6)}", "4.723902");
RIFT_TEST_CASE("{'*' * 5} {4 * '*'} {'*' * 3.0} {2.0 * '*'}", "***** **** *** **");
}

// Show the results
Expand Down

0 comments on commit e1997ce

Please sign in to comment.