1. length
Returns the number of elements in an array, packed array, string, dictionary, or name.
1.1. Syntax
array length → int packedarray length → int dict length → int string length → int name length → int
1.2. Stack Effects
| Level | Object |
|---|---|
0 |
Composite object or name |
| Level | Object |
|---|---|
0 |
|
1.3. Description
length returns the length of its operand:
-
For arrays and packed arrays: number of elements
-
For strings: number of characters (bytes)
-
For dictionaries: current number of key-value pairs (not maximum capacity)
-
For names: number of characters in the name
For dictionaries, use maxlength to get the maximum capacity.
1.5. Examples
[1 2 4] length % Returns 3
[] length % Returns 0
(abc) length % Returns 3
(hello world) length % Returns 11 (space counts)
() length % Returns 0
/mydict 5 dict def
mydict length % Returns 0 (empty)
mydict /key1 (value1) put
mydict length % Returns 1
/foo length % Returns 3
/x length % Returns 1
1.6. Common Use Cases
1.7. Common Pitfalls
Dictionary Length vs. Capacity - length returns the current number of entries, not the maximum capacity.
|
5 dict length % Returns 0, not 5
5 dict maxlength % Returns 5 (capacity)
| Name vs. String - Name length counts characters in the name, not the string representation. |
/abc length % Returns 3
(abc) length % Also returns 3
1.8. Error Conditions
| Error | Condition |
|---|---|
[ |
Object has no-access attribute |
[ |
No operand on stack |
[ |
Operand is not array, packed array, dict, string, or name |
1.9. Implementation Notes
-
Very fast operation (O(1) - length is stored with the object)
-
For arrays and strings, length is fixed at creation time
-
For dictionaries, length changes as entries are added/removed
-
Packed arrays have fixed length like regular arrays
1.11. See Also
-
get- Get element at index -
getinterval- Get subarray/substring -
forall- Iterate over all elements -
array- Create array with specific length -
string- Create string with specific length