Skip to content

Commit

Permalink
Fix for assigning strings inside loop
Browse files Browse the repository at this point in the history
Fixes #371

So this one was interesting. It's all to do with how strings get assigned: in the sample with the loop, the literal string "hello" only appears once in the source code (because it gets reused on each loop), so the parser only allocates a single value for that string. Which is fine.

BUT... assigning `hi` didn't actually create a new instance of the string, it just pointed the variable `hi` at that value, and the `rock` operator used this way actually modifies its argument instead of returning a copy. So `rock hi with "!"` is actually modifying the value that was allocated by the parser - and so on the next loop, `hi` already has the exclamation point from the previous loop.

Fixed by modifying the way the `Assign` statement works so that if you assign a string, it actually creates a copy of the string and assigns the variable to the copy, so the value allocated by the parser never gets modified.
  • Loading branch information
dylanbeattie committed Dec 31, 2024
1 parent a818b12 commit 2d68ec1
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
1 change: 1 addition & 0 deletions Starship/Rockstar.Engine/RockstarEnvironment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,7 @@ public Result Assign(Assign assign)

public Result Assign(Variable variable, Value value, Scope scope = Scope.Global) => value switch {
Functiön function => SetVariable(variable, MakeLambda(function, variable), Scope.Local),
Strïng strïng => SetVariable(variable, strïng.Clone(), scope),
_ => SetVariable(variable, value, scope)
};

Expand Down
3 changes: 3 additions & 0 deletions Starship/Rockstar.Test/Rockstar.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -1191,6 +1191,9 @@
<None Update="programs\fixtures\conditionals\if-statement.rock">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="programs\fixtures\loops\assignment-inside-loop.rock">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
(writes: Hello!Hello!Hello!)
for counter in 3
hi = "Hello"
rock hi with "!"
write hi

for counter in 3
hi = 1
hi is with 5
write hi
(writes: 666)

0 comments on commit 2d68ec1

Please sign in to comment.