There seems to be no way to check if a map key is defined. For example,
map a
a['c'] = 3
print a['b']
produces "ERROR on line 3: Map key does not exist.".
The problem is that there is no way to check if the key is defined before accessing it. That's a very big limitation on the use of map, it's not really possible to use it in most algorithms.
Proposal: we could make it work with code like
if typeof(a['b']) = type_unassigned then print "key not found"
Currently, this fails because the error would be thrown before the comparison. That can be fixed by removing the line
if (DataElement::getError()) {error->q(DataElement::getError(true),i);}
around line 1812 of Interpreter.cpp. This will let the returned element be of type type_unassigned
and the typeof
statement above would work. That's possibly not ideal, since we would also allow statements like c=a['no_key']
which would make c of unassigned type, so it would fail on a later line rather than immediately.
A more sophisticated implementation could allow a['no_key']
only within a typeof
statement.
Thoughts? Or am I completely missing some way to check if a map has a key?
After some searching in the code, I found that the "in" operator does what I want, e.g.
Unfortunately this use of "in" is not documented, but as far as code changes, the issue can be closed.