1. def
Associates a key with a value in the current dictionary.
1.2. Stack Effects
| Level | Object |
|---|---|
1 |
|
0 |
|
| Level | Object |
|---|---|
(empty) |
Current dictionary modified |
1.3. Description
def associates key with value in the current dictionary (the one on top of the dictionary stack).
-
If key already exists: replaces its value
-
If key doesn’t exist: creates new entry
If the current dictionary is in global VM and value is a composite object in local VM, [invalidaccess] error occurs.
1.5. Examples
/x 42 def % Define x as 42
/pi 3.14159 def % Define pi
/count 1 def
/count count 1 add def % count now 2
/square { dup mul } def
5 square % Returns 25
/mydict 10 dict def
mydict begin
/localVar 100 def % Goes into mydict
end
1.7. Common Pitfalls
Defines in Current Dictionary - def always uses the current dictionary (top of dict stack), not a specific dictionary.
|
% Wrong way to define in specific dict
/mydict 5 dict def
/x 42 def % Goes into userdict, not mydict!
% Right way
mydict begin
/x 42 def % Goes into mydict
end
| Global/Local VM Mixing - Cannot store local VM objects into global VM dictionaries. |
true setglobal % Global VM mode
/globalDict 10 dict def
globalDict begin
false setglobal
/localArray [1 2 3] def % Error: local in global!
true setglobal
end
| Dictionary Full (Level 1) - In Level 1, dictionary must have capacity. In Level 2, auto-expands. |
Use Literal Names - Always use literal names (starting with /) for keys.
|
1.8. Error Conditions
| Error | Condition |
|---|---|
[ |
Dictionary full (Level 1 only) |
[ |
Global VM dict receives local VM value |
[ |
Dictionary expansion exceeds limits (Level 2) |
[ |
Fewer than 2 operands on stack |
[ |
Invalid operand types |
[ |
Insufficient VM for new entry or expansion |
1.9. Implementation Notes
-
Most efficient way to create dictionary entries
-
In Level 2, may trigger dictionary expansion
-
Key typically a name, but can be any object
-
Definition is immediate (no delayed binding)