-
-
Save zacharycarter/9853400e0b55fae708b1a21b0625a342 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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