BookNote
BookNote

Reputation: 5

Series of Variables by name

In AHK script:

Code for finding a value between great numbers of variables above, for one variable:

If (Variable1 = "sin (90°)")
    MsgBox Value is reached

How searching by this method between series of variables with different value of number in their names? From Variable5 to Variable15, Variable51 to Variable105, etc.

How modify this code if number from 5 to 15, 51 to 105, or 74 to 117 etc?

number = 5
If (Variable%number% = "sin (90°)")
    .............

Is %Variable%number%% acceptable and will works surely?

And here may also be useful Associative Arrays. What is it by simple examples?

Upvotes: 0

Views: 87

Answers (3)

BookNote
BookNote

Reputation: 5

Is %Variable%number%% acceptable and will works surely?

Not. More right way

% Variable%number%

but it may have a problem.

Possible way is use Var := expression

Variable:= number

may be.

Upvotes: 0

Forivin
Forivin

Reputation: 15488

Best practice here would probably be to use an array in the first place.

myArray := []
myArray[1] := "bla"
myArray.Push("bla2") ;by using this you don't need to worry about the index number
myArray[3] := "sin (90°)"
myArray[4] := 63456

Loop % myArray.MaxIndex() 
{
    If (myArray[A_Index] = "sin (90°)")
    {
        MsgBox Value is reached
    }
}

... another example

anotherArray := []

Loop, read, C:\Files\prog.txt
{
    If (A_LoopReadLine = "FileRead, OutputVar, C:\Files\prog1.txt")
    {
        anotherArray.Push(A_LoopReadLine)
        MsgBox, An interesting code line was found. And was added to the array.
    }
    Else If (A_LoopReadLine = "blablabla")
    {
        anotherArray.Push(A_LoopReadLine)
        MsgBox, An interesting code line was found. And was added to the array.
    }
    Else If (A_LoopReadLine = "some other text line")
    {
        anotherArray.Push(A_LoopReadLine)
        MsgBox, An interesting code line was found. And was added to the array.
    } 
    ;Else
    ;{
    ;    MsgBox, Nothing important was found.
    ;}
}

Loop % anotherArray.MaxIndex() 
{
    currentArrayEntry := anotherArray[A_Index]
    MsgBox, %currentArrayEntry%
}

Upvotes: 1

woxxom
woxxom

Reputation: 73526

In an expression you can use variable expansion to modify the name of the variable to use:

number = 5
If (Variable%number% = "sin (90°)")
    .............

But consider using arrays instead.

Upvotes: 0

Related Questions