1. countdictstack

Returns the number of dictionaries currently on the dictionary stack.

1.1. Syntax

– countdictstack → int

1.2. Stack Effects

Table 1. Before
Level Object

(none)

Table 2. After
Level Object

0

int (number of dictionaries on dict stack)

1.3. Description

countdictstack counts the number of dictionaries currently on the dictionary stack and pushes this count onto the operand stack.

The count includes all dictionaries: permanent system dictionaries and any pushed by begin.

1.4. PostScript Level

Level 1 and later

1.5. Examples

Basic count
countdictstack  % Typically returns 2 or 3
                % (systemdict, [globaldict,] userdict)
With nested dictionaries
countdictstack  % Returns e.g. 3
dict1 begin
  countdictstack  % Returns 4
  dict2 begin
    countdictstack  % Returns 5
  end
end
Verifying balance
countdictstack /savedCount exch def
dict begin
  % ... operations ...
end
countdictstack savedCount eq  % Should be true

1.6. Common Use Cases

1.6.1. Stack Balance Verification

/withBalancedDict {  % dict proc =>
  countdictstack 3 1 roll
  begin
    stopped { end } if
  end
  countdictstack eq not {
    /dictstackimbalance cvx exec
  } if
} def

1.6.2. Debugging

/showDictStack {
  (Dictionary stack depth: ) print
  countdictstack =
} def

1.6.3. Cleanup Verification

countdictstack /initialDepth exch def
% ... complex operations ...
countdictstack initialDepth sub {
  end  % Pop extra dictionaries
} repeat

1.7. Common Pitfalls

Includes Permanent Dictionaries - Count includes systemdict, globaldict (Level 2), and userdict.
% Minimum stack depth varies by level:
% Level 1: 2 (systemdict, userdict)
% Level 2: 3 (systemdict, globaldict, userdict)
Use for Defensive Programming - Check dictionary stack balance in error handlers.

1.8. Error Conditions

Error Condition

[stackoverflow]

No room on operand stack (extremely rare)

1.9. Implementation Notes

  • Very fast operation (simple counter)

  • Does not modify dictionary stack

  • Typical maximum depth: 20-250 dictionaries (implementation-dependent)

1.10. Minimum Stack Depths

PostScript Level Minimum Depth

Level 1

2 (systemdict, userdict)

Level 2

3 (systemdict, globaldict, userdict)

1.11. See Also


Back to top

Copyright © 2025 Ribose. PostScript is a trademark of Adobe. Distributed under the MIT License.