There is a little problem: Whitespaces around the key or section lead to illegal character in variable name.
Code:
[pos]
x =100
y=300
Z=450
Here is the test file and function in one file together. Now you just need to start the script to test. Ini file is created from scratch and saved onto disk, every time you start the script.
Code:
/*
; ATTENTION! THIS COMMENT BLOCK IS IN INI FORMAT AND COULD BE USED AS INI FILE.
[META]
Source = http://www.autohotkey.com/forum/viewtopic.php?t=36601
Language = en
Description = If you want to create lots of variable from .ini files, this function is for you. It reads the whole file in one go and creates all the global variables.
Date = 2009-09-07
Author = Scratch
Category = File Management
Type = Library
*/
#NoEnv
SendMode Input
SetWorkingDir %A_ScriptDir%
; .....................................................
; TEST SECTION
; .....................................................
iniFile := SubStr( A_ScriptName, 1, -3 ) . "ini"
iniContent =
(
[pos]
x =100
y=300
Z=450
)
replaceFile(iniFile, iniContent)
ini(test)
msgbox posx := %posx% , posy := %posy% , posz := %posz%
;
; Now we change the variables and write/update the ini
;
posx := posx * 2
posy := posy * 2
posz := posz * 2
ini(test, 1)
Msgbox Updated variables written...
;
; To confirm the INI is correctly updated, we read out the INI again
;
ini(test)
msgbox UPDATED >>> posx := %posx% , posy := %posy% , posz := %posz%
RETURN ; END OF Auto-execution section
replaceFile(File, Content)
{
FileDelete, %File%
FileAppend, %Content%, %File%
}
Return
; .....................................................
; END OF TEST SECTION
; .....................................................
ini( filename = 0, updatemode = 0 )
;
; updates From/To a whole .ini file
;
; By default the update mode is set to 0 (Read)
; and creates variables like this:
; %Section%%Key% = %value%
;
; You don't have to state the updatemode when reading, just use
;
; update(filename)
;
; The function can be called to write back updated variables to
; the .ini by setting the updatemode to 1, like this:
;
; update(filename, 1)
;
{
Local s, c, p, key, k, write
if not filename
filename := SubStr( A_ScriptName, 1, -3 ) . "ini"
FileRead, s, %filename%
Loop, Parse, s, `n`r, %A_Space%%A_Tab%
{
c := SubStr(A_LoopField, 1, 1)
if (c="[")
key := SubStr(A_LoopField, 2, -1)
else if (c=";")
continue
else {
p := InStr(A_LoopField, "=")
if p {
k := SubStr(A_LoopField, 1, p-1)
if updatemode=0
%key%%k% := SubStr(A_LoopField, p+1)
if updatemode=1
{
write := %key%%k%
IniWrite, %write%, %filename%, %key%, %k%
}
}
}
}
}
Play with some changes on
iniContent variable to see what works.
The function
globalsFromIni() is similair to this, but it does not have a write feature. May be there is some line of code you are interested in it.
I am also working on something which works with strings formatted like an ini (seen several times, but I want to have my own solution).