Page 1 of 1

Import Variables from file

Posted: 12 Aug 2020, 14:54
by RubbeH
Hello, I don't know if this is doable but I'll give it a try.

I am wondering if it's possible to have a Script read a file, for example a .txt-file and retrieve those as variables for later use in my script?

For example a .txt-file that looks like:
aaaaa = many letters
bbbbb = some other
ccccc = and someting different
ddddd = fourth one
eeeee = fifth one

And what I'm looking to do is something like this:

Code: Select all

FileRead, C:\Desktop\Test\testing.txt
Msgbox, %aaaaa% ; MessageBox should read "many letters"
MsgBox, %bbbbb% ; MessageBox should read "some other"
MsgBox, %ccccc% ; MessageBox should read "and something different"
Obviously there's a bunch of code before and after the above :D

Additional information, this .txt-file will probably contain about 5 thousand different variables with minor changes daily so I'd rather not put it in my .ahk-script.

Re: Import Variables from file

Posted: 12 Aug 2020, 15:26
by Chunjee
it is possible.
I like json files best. https://github.com/G33kDude/AutoHotkey-JSON or https://github.com/Chunjee/json.ahk

You can also use ini file(s)
this is more built in to vanilla ahk, but for a large number of vars you should use a library https://www.autohotkey.com/boards/viewtopic.php?t=62562

Re: Import Variables from file

Posted: 12 Aug 2020, 16:30
by BoBo

Code: Select all

FileRead, content, C:\Desktop\Test\testing.txt
arr := StrSplit(content,"`n")
Msgbox,% StrSplit(arr[1],"=").2 ; MessageBox should read "many letters"
MsgBox,% StrSplit(arr[2],"=").2 ; MessageBox should read "some other"
MsgBox,% StrSplit(arr[3],"=").2 ; MessageBox should read "and something different"
Not tested.

Re: Import Variables from file  Topic is solved

Posted: 12 Aug 2020, 17:14
by A_AhkUser
Both the Ini and JSON data-interchange formats have an advantage that can be significant; data can be layered.
Here's a another possible solution for a non-hierarchical list a key-values pairs (cf. convert list to simple array):

Code: Select all

file := FileOpen(A_Desktop . "\testing.txt", 4, "UTF-8") ; 4 (0x4) replaces `r`n with `n when reading
text := file.read()
delimiters := ["=", "`n"]
trailingCharsToOmit := A_Space . A_Tab
obj := Object(StrSplit(text, delimiters, trailingCharsToOmit)*) ; https://www.autohotkey.com/boards/viewtopic.php?f=5&t=33663
file.close()

MsgBox % obj["aaaaa"]
MsgBox % obj.haskey("bbbbb")
MsgBox % obj.haskey("zzzzz")
MsgBox % obj.count()

for k, v in obj
	MsgBox % k " > " v

A_AhkUser

Re: Import Variables from file

Posted: 13 Aug 2020, 08:32
by RubbeH
A_AhkUser wrote:
12 Aug 2020, 17:14
Both the Ini and JSON data-interchange formats have an advantage that can be significant; data can be layered.

A_AhkUser
Thanks! :thumbup: