If you move the definition of word to the beginning of the file, it should work
fine. Global variables in Nim are simply declared outside of procs, before
usage anywhere in the file. So this should work fine:
# I am command line version
var word = CreateObject("Word.Application")
proc checkHeading() =
word.Selection.HomeKey(...) # **this line can't find variant word,
so the compilation can't succeed**
do some check on Heading, then display message
proc checkPunctation() =
word.Selection.HomeKey(...)
do some check on punctaion, then display message
proc check(fn)=
word.Documents.Open(fn, True)
checkHeading()
checkPunctation()
when isMainModule:
check(r"c:\test.doc")
Run
The reason it doesn't work if you have it like this:
proc checkHeading() =
word.Selection.HomeKey(...)
do some check on Heading, then display message
proc checkPunctation() =
word.Selection.HomeKey(...)
do some check on punctaion, then display message
proc check(fn):
word.Documents.Open(fn, True)
checkHeading()
checkPunctation()
var word = CreateObject("Word.Application") # needs to be declared first
before it is used
Run
is because Nim's parsing semantics are different than Python's. Python's
statements are parsed top level first, so as long as a variable is declared
somewhere in the file, you can use it within a function. But Nim parses the
whole file top to bottom, so if the compiler sees `word` here:
proc checkHeading() =
word.Selection.HomeKey(...) # **this line can't find variant word,
so the compilation can't succeed**
do some check on Heading, then display message
Run
and doesn't have a definition for it, it will throw an error. Alternatively, if
you don't want to initialize word at the top of the file, you can declare it at
the top like so:
var word: ObjectType # Replace "ObjectType" with the type that CreateObject
returns
...
proc check(fn)=
word = CreateObject("Word.Application")
word.Documents.Open(fn, True)
checkHeading()
checkPunctation()
Run