Firstly, I really appreciate all the help I get from the "Nimistas" here on the forum. Invaluable!
Secondly, there is again something I can't figure out:
I want to pass a string parameter to a procedure with a default from the main object the procedure operates on:
proc warmItUp(self: TheCoolThing, myStr = self.theStr): string = ...
This obviously doesn't work. So I thought I set the myStr parameter to nil and test for this:
proc warmItUp(self: TheCoolThing, myStr: string = nil): string =
if myStr == nil:
myStr = self.theStr
...
This doesn't compile either because of a typing error (after all nil is not of type string). How can I set in Nim a string parameter of a procedure by default to nil?
string is a non-nilable type, which means you cannot, but fear not we have the options module!
import options
proc warmItUp(self: TheCoolThing, myStr = none(string)): string =
if myStr.isSome:
self.theStr = myStr.get # I assume you wrote this backwards initially.
Beauty!
I often look in the wrong spot: Nim realises many things in its standard library what other languages implement in the language syntax.
Does it have to be nil/none, or can it be just an empty string?
proc warmItUp(self: TheCoolThing, myStr = ""): string =
var myStr = myStr
if myStr.len == 0:
myStr = self.theStr
...
You can also use overloading.
proc warmItUp(self: TheCoolThing): string =
myStr = self.theStr
...
proc warmItUp(self: TheCoolThing, myStr: string): string =
...
Solution with options feels more like anti-pattern, as it would force you to use arg.some everywhere you are calling that function and specifying the argument. Overloading looks much better.
Nim
import options
proc somefn(a: int, b = string.none): void = discard
somefn(1)
somefn(1, "s") # <= Error
or, potentially less verbosely:
proc warmItUp(self: TheCoolThing, myStr: string): string = discard
proc warmItUp(self: TheCoolThing): string = warmItUp(self,self.theStr)
...