Thank you very much for the excellent explanation. It all makes so much sense
now.
I combined **PMunch** 's suggustion plus a small variant of your second option.
to yield:
type
Callback = proc(name: string, length: int)
TestOptions = object
name: string
length: int
callback: Callback
const show = proc(name: string, length: int) =
echo "Callback executed: ", name, " is ", length, " inches long"
let option1 = TestOptions(name: "foot", length: 12)
let option2 = TestOptions(name: "inch", length: 1)
let option3 = TestOptions(name: "yard", length: 36, callback: show)
proc test(options: TestOptions) =
if options.callback.isNil:
echo "No callback supplied"
else:
options.callback(options.name, options.length)
test option1
test option2
test option3
Run
which gives the desired result:
nim r tests/test_options.nim
No callback supplied
No callback supplied
Callback executed: yard is 36 inches long
Run
Lessons learned:
* A normal **unnamed proc** type defaults to a type **closure** so you can
have an environment.
* Procedures are a simply pointer type and so **isNil** is available for
checking if defined.