[12.5] How can I define a stack?

The best way to define abstract data types is to use parent scripts. As an example, this is from Kurt Cagle (CagleK@aol.com):
-- this is movie script "stack object"

property stack

on birth me
  set stack=[]
  return me
end birth

on push me,entry
  add stack,entry
  return entry
end push

on pop me
  if count(stack)>0 then
    set entry=getLast(stack)
    deleteAt stack,count(stack)
    return entry
  else
   return #empty
  end if
end pop
-- additional stack operations can also be defined in such a script -- (and Kurt did) but for the present let's keep to the basics

To create a stack you'd use:

  put birth(script "stack object") into myStack
You can then push & pop from it by simply saying:
  push myStack, myValue
  set popValue = pop(myStack)
If you don't want to use parent scripts & objects, you can also create abstract data types in a more traditional functional fashion. The difference in this case is minimal:
-- non-object version of the stack data type
-- this goes in a movie script

on newStack
  return []
end newStack

on isEmpty stack
  return count(stack)=0
end isEmpty

on push stack, item
  add stack, item
end push

on pop stack
  if count(stack)>0 then
    set entry = getLast(stack)
    deleteAt stack, count(stack)
    return entry
  else
    return #empty
  end if
end pop
Useage would be the same, except that to create the stack you'd use:
  put newStack() into myStack
Objects have the advantage that they carry their methods with them wherever they go, and could for instance be passed to another movie in which the stack handlers themselves are not explicitly defined. They are also more enclosed, so there is less risk of confusing the stack data type with its implementation in Director lists (as an example of why this is desirable, consider the results of mistakenly "sort"-ing your stack).

Bearing this in mind, the next data type examples will be given using objects only. (For more info on parent scripts and child objects, see section 14.)