How can I perform a math expression using a string the script receives via command line? Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
gaberiel__2
Posts: 14
Joined: 18 Jan 2023, 14:18

How can I perform a math expression using a string the script receives via command line?

Post by gaberiel__2 » 01 Apr 2023, 10:41

I have this small program that uses AHK as its back end engine. In this program, I would like to implement a "variables" feature to perform very basic math operations (addition/multiplication etc).

the variables/objects being referenced are predefined in the AHK script being called via command line.
.\Shift_IN.Ahk "$Start-5"
.\Shift_OUT.Ahk "$End+5"

A condensed example of a script I would call is:

Code: Select all

; A_args[1] := "$Start-5"                        ;An example of an incoming string
Input   := StrReplace(Parameters[1],"$",,null)   ;Remove the "$" symbol, last parameters seems to be mandatory, I gave it null 

Start   := 25                                    ;<---- minus 5 this variable
Current := 7   
End     := 50  

NewStartFrameIs := % %input%                     ;<---- I am assuming  that I placed "start-5" here         
MsgBox, % "NewStartFrameIs: " NewStartFrameIs    ;NewStartFrameIs's value should be 20
The script does not run though, I get errors, the most common being:

Code: Select all

 ERROR :--->   NewStartFrameIs := % %input% ... contains an illegal character:
when I tried this NewStartFrameIs := %input% I also got the same error
How can I get AHK to think the % %input% is an expression I want it to perform and not a string?

Any help would be greatly appreciated!

User avatar
mikeyww
Posts: 27096
Joined: 09 Sep 2014, 18:38

Re: How can I perform a math expression using a string the script receives via command line?  Topic is solved

Post by mikeyww » 01 Apr 2023, 11:00

Hello,

I think that a bunch of calculator scripts have already been posted.

Code: Select all

#Requires AutoHotkey v1.1.33
expr    := A_Args[1]
varList := ["Start", "Current", "End"]
Start   := 25
Current := 7
End     := 50  
For each, var in varList
 expr := StrReplace(expr, "$" var, %var%)
MsgBox 64, Calculation, % expr = "" ? "N/A" : expr "`n`n= " eval(expr)

eval(exp) { ; Adapted from flyingDman: https://www.autohotkey.com/boards/viewtopic.php?p=456287#p456287
 exec := ComObjCreate("WScript.Shell").Exec("AutoHotkey.exe /ErrorStdOut *")
 exec.StdIn.Write("FileAppend, % (" StrReplace(exp, "PI", ACos(-1)) "), *"), exec.StdIn.Close()
 Return exec.StdOut.ReadAll()
}

gaberiel__2
Posts: 14
Joined: 18 Jan 2023, 14:18

Re: How can I perform a math expression using a string the script receives via command line?

Post by gaberiel__2 » 01 Apr 2023, 17:44

This is exactly what I had in mind but could not express it in words. I will trawl the internet for more of these calculator examples. Thanks for helping once again!


Post Reply

Return to “Ask for Help (v1)”