Why is my string nil?
I made this simple program that reads characters until the enter key is pressed var data: string while true: var c = readChar(stdin) # read char case c of '\r': # if enter, stop break else: discard data.add(c) # add the read character to the string echo data But when it tries to echo data, it crashes > ./program hello Traceback (most recent call last) program.nim(11) program SIGSEGV: Illegal storage access. (Attempt to read from nil?) This means data is nil. But every time I press enter a character, it adds the character to data. Something goes wrong, but where?
data is initially nil when you define it as var data: string. Instead you can use var data = "" to make it an initialized string.
The stream stdin buffers all the characters until the newline key is pressed, then it will submit the character(s). I expected the behavior to be reading direct characters. That means that \r will never be the case, it will try to add a character to data but data is nil, so that fails. I thought it failed at the echo statement. To demonstrate, this code works: var data = "" while true: var c = readChar(stdin) # read char case c of '\e': # if escape, stop break else: data.add(c) # add the read character to the string echo data
MD5 on an array, array[0..63, uint8] to cstring conversion
Converting a seq[char] to string
Nim: On mac, cannot open standard import
How to compare two typedesc in a template for equality
Is there a “default” file name that can be used for importing modules?
Unable to get StringStream created from marshal to output the data
Initialize a seq of seqs
How to change Nim compiler output file location and name
Compile-time Call Count in Nim
How To Convert Slice To Sequence?
Cannonical way to do circular dependency in Nim
toSeq(some_string) Type Mismatch
Why is there a warning not to use system.cmp[string] for Nim string comparison
What's the the best way to get the current operating system?
How to get the type of a value as string?
Loop results to array