Table of Contents
1. known
Tests whether a specific dictionary contains a given key.
1.2. Stack Effects
| Level | Object |
|---|---|
1 |
|
0 |
|
| Level | Object |
|---|---|
0 |
|
1.3. Description
known returns true if there is an entry in dictionary dict whose key is key. Otherwise, it returns false.
The dictionary does not need to be on the dictionary stack - it can be any dictionary object.
1.5. Examples
Checking for key
/mydict 5 dict def
mydict /total 0 put
mydict /total known % Returns true
mydict /badname known % Returns false
Conditional definition
currentdict /myvar known not {
/myvar defaultValue def
} if
Safe access
dict /key known {
dict /key get
% Use value
} {
% Use default
} ifelse
1.6. Common Use Cases
1.6.1. Checking Before Access
/safeGet { % dict key => value or null
2 copy known {
get
} {
pop pop null
} ifelse
} def
1.7. Common Pitfalls
Checks Specific Dictionary Only - known does NOT search the dictionary stack, only the specified dictionary.
|
/x 42 def % In current dict
5 dict /x known % Returns false (wrong dict!)
currentdict /x known % Returns true
Use for Validation - Check before get to avoid [undefined] errors.
|
1.8. Error Conditions
| Error | Condition |
|---|---|
[ |
Dictionary has no-access attribute |
[ |
Fewer than 2 operands on stack |
[ |
First operand not a dictionary |