Page 1 of 1

Text in a function as a variable

Posted: 05 May 2024, 05:58
by Draken
Hello, it's a shame, but I keep missing the basics. How to insert a variable as text, but at the same time make it work with variables?
In this case, equations1 and equations2 are calculated only once and after the variable (equations1 and equations2) there is a result which does not change depending on the change of x and y. Thank you

Code: Select all

#Requires AutoHotkey v2.0
x := 0
y := 0
result1 := 2
result2 := 2.5
equations1 := x + y
equations2 := 0.5*x+2*y

loop{
    if (equations1 = result1)
        MsgBox("Yes")
    else
        MsgBox("No")
    
    if (equations2 = result2)
        MsgBox("Yes")
    else
        MsgBox("No")
x++
y++
}

Re: Text in a function as a variable

Posted: 05 May 2024, 06:12
by boiler
Just because you once assign the results of an expression to a variable, that doesn't link that expression to that variable. That's what functions are for:

Code: Select all

#Requires AutoHotkey v2.0
x := 0
y := 0
result1 := 2
result2 := 2.5
equations1() {
	return x + y
}
equations2() {
	return 0.5*x+2*y
}

loop{
    if (equations1() = result1)
        MsgBox("Yes")
    else
        MsgBox("No")
    
    if (equations2() = result2)
        MsgBox("Yes")
    else
        MsgBox("No")
x++
y++
}

Re: Text in a function as a variable

Posted: 05 May 2024, 06:49
by Draken
@boiler
Ok thank you, and how do I make the equation change? For example, by inserting it at the beginning of the script using InputBox or from Gui?

Re: Text in a function as a variable  Topic is solved

Posted: 05 May 2024, 06:54
by boiler
You generally can't change expressions in a script dynamically. There have been some "evaluate" functions posted on the forum that will allow a string to be evaluated as if it were an AHK expression, so you could look into those. Or you could have a number of different expressions available to be executed conditionally based on the user's input or something, but generally you cannot just define an expression dynamically and have AHK evaluate it.

By the way, my example of using functions that base their calculations on global variables was just to make it look more similar to your original script. It's best to write functions where you pass values to them as parameters, and their local variables are used inside the function:

Code: Select all

#Requires AutoHotkey v2.0
x := 0
y := 0
result1 := 2
result2 := 2.5
equations1(a, b) {
	return a + b
}
equations2(a, b) {
	return 0.5*a+2*b
}

loop{
    if (equations1(x, y) = result1)
        MsgBox("Yes")
    else
        MsgBox("No")
    
    if (equations2(x, y) = result2)
        MsgBox("Yes")
    else
        MsgBox("No")
x++
y++
}