PDA

View Full Version : Here's a script to load and save settings



martin
18-06-2009, 11:49
Here's a script with 2 very simple functions to load and save (multiple) settings. Maybe others find it usefull too.


uses "file"

function tbmain()
'save some settings to settings.txt
SaveSetting "Player1Name","Martin"
SaveSetting "Player2Name","Richard"

'load the settings from settings.txt
msgbox 0,"Player 1: " & LoadSetting("Player1Name")
msgbox 0,"Player 2: " & LoadSetting("Player2Name")

saveSetting "Player2Name","Deborah" 'change name of player2
msgbox 0,"Player 2: " & LoadSetting("Player2Name")
end function

function Loadsetting(tag as string) as string
if file_exists(APP_ScriptPath & "settings.txt") then function=grab$(file_load(APP_ScriptPath & "settings.txt"),"<" & tag & ">","</" & tag & ">")
end function

function SaveSetting(tag as string,txt as string)
local oldline,Content as string

if file_exists(APP_ScriptPath & "settings.txt") then
Content=file_load(APP_ScriptPath & "settings.txt")
oldline="<" & tag & ">" & grab$(Content,"<" & tag & ">","</" & tag & ">") & "</" & tag & ">"

if grab$(Content,"<" & tag & ">","</" & tag & ">")="" then
Content+=$crlf & "<" & tag & ">" & txt & "</" & tag & ">"
else
Content=replace$(Content,oldline,"<" & tag & ">" & txt & "</" & tag & ">")
end if
end if

if Content="" then Content="<" & tag & ">" & txt & "</" & tag & ">"

file_save(APP_ScriptPath & "settings.txt",Content)
end function

martin
19-06-2009, 17:23
I replaced the script above with improved code because there was a bug in it. It works fine now.

Petr Schreiber
19-06-2009, 18:00
Hi Martin,

very XMLish :)
Grab$ is very powerful function. Instead of Replace$, I would recommend having a look at Patch$ function.
It seeks tags, and replaces text between them, which is exactly what is needed here. It is something like inverse function to Grab$.

martin
19-06-2009, 20:09
Hi Petr,

Thanx for the tip (patch), i will check it out!
And you're right: GRAB$ is a great Thinbasic-keyword. I use it many, many times for these kind of things. Also great to analyze html or xml.

Martin

Michael Hartlef
19-06-2009, 21:12
Thanks martin, this really looks interesting!