Skip to main content

Using %Push and %Pop with Dynamic Arrays

Using %Push and %Pop with Dynamic Arrays

The %Push() and %Pop() methods are only available for dynamic arrays. They are work exactly like %Set() and %Remove() except that they always add or remove the last element of the array. For example, the following code produces the same results with either set of methods (see “Method Chaining” for details about calling %Set() or %Push() several times in the same statement):

   set array = []
   do array.%Set(array.%Size(), 123).%Set(array.%Size(), 456)
   write "removed "_array.%Remove(array.%Size()-1)_", leaving "_array.%ToJSON()

removed 456, leaving [123]

   set array = []
   do array.%Push(123).%Push(456)
   write "removed "_array.%Pop()_", leaving "_array.%ToJSON()

removed 456, leaving [123]

Although %Push() and %Pop() are intended for stack operations, you could implement a queue by substituting %Remove(0) for %Pop().

The following example builds an array with %Push(), and then removes each element in reverse order with %Pop().

Using %Push() and %Pop() to build an array and tear it down

Build an array containing a nested array. The final call to %Push() specifies the optional type argument to store a boolean value as JSON false rather than ObjectScript 0 (see “Overriding a Default Datatype with %Set() or %Push()”):

   set array=[]
   do array.%Push(42).%Push("abc").%Push([])
   do array."2".%Push("X").%Push(0,"boolean")
   write array.%ToJSON()

[42,"abc",["X",false]]

Remove all elements of the nested array. Like all dynamic entity methods, %Pop() will return ObjectScript 0 rather than JSON false:

   for i=0:1:1 {write "/"_array."2".%Pop()_"/ "}
/0/ /X/

   write array.%ToJSON()
[42,"abc",[]]

Now remove all elements of the main array, including the empty nested array:

   for i=0:1:2 {write "/"_array.%Pop()_"/ "}
/2@%Library.DynamicArray/ /abc/ /42/

   write array.%ToJSON()
[]

These examples use hard coded for loops for simplicity. See “Sparse Array Iteration with %Size()” for more realistic examples of array iteration.

FeedbackOpens in a new tab