|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching • Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
Read from stdin -- advanced solutionWhen I wanted to use a colored prompt and/or when I wanted to type in some Unicode text, then the previous (intermediate) solution was not perfect. The solution that I show here worked for me under Linux. We'll need the 3rd-party library noise: $ nimble install noise import pkg/noise import std/random proc input(noise: var Noise): string {.raises: [EOFError, IOError, Exception].} = let ok = noise.readLine() if not ok: raise newException(EOFError, "abort") noise.getLine() proc input(noise: var Noise, prompt: Styler): string {.raises: [EOFError, IOError, Exception].} = noise.setPrompt(prompt) noise.input() proc input(noise: var Noise, prompt: string): string {.raises: [EOFError, IOError, Exception].} = noise.setPrompt(Styler.init(prompt)) noise.input() proc main() = randomize() # var noise = Noise.init() let prompt = Styler.init(bgCyan, "JKB", resetStyle, "> ") noise.setPrompt(prompt) echo "'", noise.input(), "'" # v1 echo "'", noise.input("> "), "'" # v2 # while true: try: let s = block: let which = rand(1..2) if which == 1: noise.input(Styler.init(bgRed, fgWhite, styleBright, "Error", resetStyle, "> ")) # v3 else: noise.input(Styler.init(bgGreen, fgWhite, styleBright, "OK", resetStyle, "> ")) # v4 echo "'" & s & "'" except EOFError: break main() The library implicitly imports the What do we get?
Note:
History support
proc main() = var noise = Noise.init() # while true: try: let s = noise.input("> ") echo "'", s, "'" if s.len > 0: # this noise.historyAdd(s) # and this except EOFError: break |
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |