1. getinterval
Extracts a subsequence from an array, packed array, or string.
1.1. Syntax
array index count getinterval → subarray packedarray index count getinterval → subarray string index count getinterval → substring
1.2. Stack Effects
| Level | Object |
|---|---|
2 |
|
1 |
|
0 |
|
| Level | Object |
|---|---|
0 |
Subarray or substring |
1.3. Description
getinterval creates a new array, packed array, or string object whose value consists of count elements starting at position index in the original object.
The elements in the subsequence are shared between the original and new objects - modifying one affects the other.
Requirements: * index must be valid (0 to length-1) * count must be non-negative * index + count must not exceed the original length
1.5. Examples
[9 8 7 6 5] 1 3 getinterval % Returns [8 7 6]
(abcde) 1 3 getinterval % Returns (bcd)
(abcde) 0 0 getinterval % Returns () (empty)
/orig [1 2 3 4 5] def
orig 1 3 getinterval
/sub exch def % sub = [2 3 4]
sub 0 99 put % Modify sub
orig % Now [1 99 3 4 5]
1.6. Common Use Cases
1.7. Common Pitfalls
| Shared Values - The subarray/substring shares elements with the original. Modifications affect both! |
[1 [2] 3] 1 1 getinterval dup 0 get
0 99 put % Modifies BOTH arrays!
| Zero-Based Indexing - Remember that index starts at 0, not 1. |
(abc) 1 2 getinterval % Returns (bc), not (ab)
| Range Validation - index + count must not exceed length. |
[1 2 3] 2 2 getinterval % Error: 2+2 > 3
| Empty Intervals - count can be 0, which returns an empty array/string. |
1.8. Error Conditions
| Error | Condition |
|---|---|
[ |
Object has no-access attribute |
[ |
index or count invalid, or index + count > length |
[ |
Fewer than 3 operands on stack |
[ |
Wrong operand types |
1.9. Implementation Notes
-
Creates a new object header but shares the underlying data
-
Very efficient - no data copying occurs
-
The returned object has same access attributes as original
-
For packed arrays, returns a packed array
1.10. Performance Considerations
-
Creating intervals is very fast (O(1))
-
No memory copying - elements are shared
-
Useful for working with portions of large arrays/strings without duplication
1.11. See Also
-
putinterval- Insert array/string into another -
get- Get single element -
length- Get length -
aload- Load all elements onto stack