ObjectsList := ["In","Out", "Dogs"]
In := 50
Out := 100
Dogs := 5
For each, Obj in ObjectsList
RawArgs := StrReplace(A_Args[1], "$" Obj, %Obj%)
msgbox, % RawArgs
If I run the above code as a script via command line (.\somepath\AHKScript.ahk '$In-5,$Out-50'
). I am expecting, RawArgs
to be 50-5,100-50
but instead I get $In-5,$Out-50
.
While the following code I get what I am expecting to get, which is 50-5,100-50
:
RawArgs := "$In-5,$Out-50"
ObjectsList := ["In","Out", "Dogs"]
In := 50
Out := 100
Dogs := 5
For each, Obj in ObjectsList
RawArgs := StrReplace(RawArgs, "$" Obj, %obj%)
OutputDebug, % RawArgs
I tried getting to the bottom of this but to no avail. what am I doing wrong?
It's because you're just reassigning to RawArgs
every time. You do indeed replace successfully each time, but you just immediately overwrite and discard the result during the next cycle of the for-loop. And because your last search is for "Dogs", which doesn't exist, nothing gets replaced and you're left with the original string.
Also, you really should forget about dynamic variables. It's just super legacy.
Here's one way you could do your script:
output := A_Args[1]
ObjectsList := { "In": 50
, "Out": 100
, "Dogs": 5 }
for key, value in ObjectsList
output := StrReplace(output, "$" key, value)
MsgBox, % output
Although a regex approach could be more suitable.