Hi Xander,
In my opinion, when using LISP, data can be manipulated a lot easier using lists. Hence I would use a function similar to this:
(defun XParseData ( file / line sub lst i m )
(if (and (setq file (findfile file)) (setq file (open file "r")))
(progn
(while (setq line (read-line file))
(cond
( (eq "[" (substr line 1 1))
(if sub (setq lst (cons (reverse sub) lst)))
(setq sub (list (substr line 2 (- (strlen line) 2))))
)
( (or (eq "" line) (eq "#" (substr line 1 1))) )
(t
(setq i 0 m (strlen line))
(while (and (<= (setq i (1+ i)) m) (/= "=" (substr line i 1))))
(if (<= i m)
(setq sub (cons (cons (substr line 1 (1- i)) (substr line (1+ i))) sub))
)
)
)
)
(close file)
(if sub (setq lst (cons (reverse sub) lst)))
)
)
(reverse lst)
)
To parse the config file into an association list, which may be manipulated with much less code. Note that the code is quite verbose since the use of Visual LISP functions is not allowed.
The above function will read a file such as:
[SECTION1]
KEY1=VALUE1
KEY2=VALUE2
[SECTION2]
KEYA=VALUEA
KEYB=VALUEB
#this is a comment
[SECTION3]
KEYX=VALUEX
KEYY=VALUEY
#end
And return a list:
(
("SECTION1"
("KEY1" . "VALUE1")
("KEY2" . "VALUE2")
)
("SECTION2"
("KEYA" . "VALUEA")
("KEYB" . "VALUEB")
)
("SECTION3"
("KEYX" . "VALUEX")
("KEYY" . "VALUEY")
)
)
Now the above list can be queried using LISP's assoc functions:
(defun XGetValue ( alist section key )
(if (setq section (cdr (assoc section alist))) (cdr (assoc key section)))
)
(setq lst (XParseData "C:\\SomeFolder\\SomeFile.ini"))
(XGetValue lst "SECTION2" "KEYB")
==> "VALUEB"
Writing is a different issue however, since the above list is devoid of comments.
Lee