Yamen
Yamen

Reputation: 35

Looking up data from a file, and storing them as variables

I'm new to autohotkey and I can't figure out how to solve this. Any help is appreciated. I have list.txt which includes ids and names like this:

list.txt:
123124 - whatever
834019 - sometext
3980   - afjalkfj

I need a function that can do the following

lookup(id, name){
    ** The function here should lookup for the id inserted 
 then save ONLY the data related to it in variable x (not the full line)
}

Example

lookup(834019, x)
%x% = sometext

Please help me to do this. Thanks!

Upvotes: 2

Views: 146

Answers (1)

Relax
Relax

Reputation: 10543

What you need in this case are

  • FileRead to read the file's contents into a variable.

  • A parsing loop to parse the text of each line.

  • The StrSplit() function to split the text of each line into an array of Substrings using the specified Delimiters.

The second parameter (name) is redundant in this case. You can omit it:

x := lookup(834019)
MsgBox, % x

MsgBox, % lookup(3980)


lookup(id) {
    FileRead, Contents, list.txt   ; read the file's contents into the variable "Contents"
    if not ErrorLevel  ; Successfully loaded.
    {
        Loop, parse, Contents, `n, `r  ; parse the text of each line 
        {
            word_array1 := StrSplit(A_LoopField," - ").1  ; store the first substring into the variable "word_array1"
            word_array1 := Trim(word_array1, " `t") ; trim spaces and tabs in this variable
            If (word_array1 = id)
            {
                name := StrSplit(A_LoopField," - ").2
                name := Trim(name, " `t")
                return name
            }
        }
        Contents := ""  ; Free the memory.
    }
    else
        MsgBox, A problem has been encountered while loading the File Contents
}

Upvotes: 1

Related Questions