Hi, I need help with the following.
type
MyObj = object
id: string
var stuff: MyObj
template t*(dest: untyped): string =
when declaredInScope(dest):
"in scope"
else:
"not in scope"
stuff.id = "c"
echo "stuff is " & t(stuff)
echo "stuff.id is " & t(stuff.id)
var z = "0"
echo "z is " & t(z)
echo "k s " & t(k)
This generates:
stuff is in scope
stuff.id is not in scope
z is in scope
k is not in scope
The output makes sense, except for stuff.id - why is it not in scope (undeclared)? stuff.id is no different from z .. they are both strings that are declared.
x has to be an identifier.
stuff.id is not an identifier. declared may work in this case (I'm not sure).
Citation from: http://nim-lang.org/docs/manual.html#definitions
"An identifier is a symbol declared as a name for a variable, type, procedure, etc. The region of the program over which a declaration applies is called the scope of the declaration."
"Identifiers in Nim can be any string of letters, digits and underscores, beginning with a letter."
AFAIS stuff is an identifier stuff.id is an expression. The . is an operator which selects the field of the object and its meaning is the value of that field. The identifiers scope is equal to the scope of the fields of the object. Just that the declaredInScope() only works for the identifier itself.
You may ask for compiles():
type
MyObj = object
id: string
var stuff: MyObj
template t*(dest: untyped): string =
when compiles(dest):
"in scope"
else:
"not in scope"
stuff.id = "c"
echo "stuff is " & t(stuff) # in scope
echo "stuff.id is " & t(stuff.id) # in scope
echo "stuff.bla is " & t(stuff.bla) # not in scope
It works! I've looked at the docs a long time but some things are difficult to understand until they are used in practice, but in hindsight it seems obvious: "This can be used to check whether a type supports some operation". Thank you, OderWat.
(BTW I think this is a "textbook" case of a problem with Nim's documentation. The function has all of two sentences essentially making it a glossary not a manual. If it was the Python manual, for example, there would have been a full page with multiple examples and a "see also" section linking to declaredInScope() since they are related by functionality making it easier to piece things together).