I'm working a 'save game' mechanism and had the need for reading and writing key value pairs so knocked up a little script, thought maybe someone else would maybe find it useful, also for tips on my AppGameKit coding!
type KVP_INFO
Key AS STRING
Value AS STRING
endtype
Global _KVP AS KVP_INFO[0]
Global _KVP_Delimiter$ = "|"
// internal
function _KVP_KeyIndex(Key$)
for index = 0 to _KVP.length
if _KVP[index].Key = Key$
exitfunction index
endif
next index
endfunction -1
// public
function KVP_Count()
exitfunction _KVP.length - 1
endfunction -1
function KVP_SetValue(Key$, Value$)
index = _KVP_KeyIndex(Key$)
if index > -1
_KVP[index].Value = Value$
else
tmp AS KVP_INFO
tmp.Key = Key$
tmp.Value = Value$
_KVP.insert(tmp)
endif
endfunction
function KVP_GetValue(Key$, DefValue$)
index = _KVP_KeyIndex(Key$)
if index > -1
result$ = _KVP[index].Value
else
result$ = DefValue$
endif
endfunction result$
function KVP_Save(File$)
fileID = OpenToWrite(File$, 0)
for index = 1 to _KVP.length
WriteLine(fileID, _KVP[index].Key + _KVP_Delimiter$ + _KVP[index].Value)
next index
CloseFile(fileID)
endfunction
function KVP_Load(File$)
_KVP.length = 0
fileID = OpenToRead(File$)
while FileEOF(fileid) = 0
cLine$ = ReadLine(fileid)
tmp AS KVP_INFO
tmp.Key = GetStringToken(cLine$, _KVP_Delimiter$, 1)
tmp.Value = GetStringToken(cLine$, _KVP_Delimiter$, 2)
_KVP.insert(tmp)
endwhile
CloseFile(fileID)
endfunction
and a usage example
// saving
// add 100 key-value pairs
item = 0
for Key = 1 to 100
inc item, 1
KVP_SetValue("Key"+str(Key), "K-"+str(Key)+ " Value "+str(item))
next Key
KVP_Save("test")
// loading
KVP_Load("test")
for Key = 1 to KVP_Count()
Log(KVP_GetValue("Key"+str(Key), "Default Value!"))
next Key