Skip to content

Instantly share code, notes, and snippets.

@zacharycarter
Created September 14, 2019 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zacharycarter/9853400e0b55fae708b1a21b0625a342 to your computer and use it in GitHub Desktop.
Save zacharycarter/9853400e0b55fae708b1a21b0625a342 to your computer and use it in GitHub Desktop.
import parsecfg, streams, strutils, tables
type
ConfigEntryKind* = enum
cekInt
cekString
cekCount
ConfigEntry* = object
case kind*: ConfigEntryKind
of cekInt:
i*: int
of cekString:
s*: string
of cekCount:
discard
Config* = object
entries*: Table[string, ConfigEntry]
success: bool
proc loadConfig*(path: string): Config =
var f = newFileStream(path, fmRead)
if f != nil:
var p: CfgParser
open(p, f, path)
while true:
var e = next(p)
case e.kind
of cfgEof: break
of cfgSectionStart: ## a ``[section]`` has been parsed
continue
of cfgKeyValuePair:
var entry: ConfigEntry
case $typeof(e.value)
of "int":
entry = ConfigEntry(kind: cekInt, i: parseInt(e.value))
of "string":
entry = ConfigEntry(kind: cekString, s: e.value)
else:
entry.kind = cekCount
result.entries.add(e.key, entry)
of cfgOption:
continue
of cfgError:
continue
close(p)
else:
echo("cannot open: " & path)
result.success = false
result.success = true
echo result
let
conf = loadConfig("conf.ini")
width = conf.entries["window_width"].i
height = conf.entries["window_height"].i
# Error: unhandled exception: i is not accessible [FieldError]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment