we have isTeleporting and playerTeleports to keep track of players and the locations
they've teleported to and from.
We're checking to see if our isTeleporting list contains this player already. If it
doesn't, we'll add it—this player has just started teleporting. If the isTeleporting
list already contains this player, then we should ignore this event (and remove
the player from the list). That means we generated this event ourselves, and
we don't want our own teleport to trigger the teleport, because it would keep
doing that forever. So we throw this extra teleport event out.
If this player has teleported before, we'll get a locs from the playerTeleports hash
(a hash of locations) using the player as a key. We'll add this location to the
existing list. If this is the player's first time teleporting, we'll make a new list
(of Location s) and add this location as its first entry.
But this is no ordinary list. It's a kind of list, all right, but it's a Stack , not a
plain list. A Stack works like a stack of pancakes. You add to the top of the
stack, and when you remove a pancake it comes off the top of the stack. That's
the model we want for our list of places we've teleported. As you teleport, each
location is added to the top of the stack—and it's the top one you want to go
back to next, then the one under that, and so on.
To add an object to the top of a stack, you push it on. To get the value and
remove the object at the top, you pop it off. To just check on the top value
without removing it, you can peek at it.
As players teleport around, we'll keep a stack of each of their teleport locations,
stored in a Stack in our playerTeleports variable. We can get to the stack using
the Player object as a key. You can see what this looks like on page 132 .
Finally, we get down to backCommand . When we get a back command, we'll get
the player's list of teleport locations (if there is one), and peek at the location
on the top of the stack, saving that in loc for now.
Maybe we teleported to this spot and haven't moved yet. In that case, we'd
want to go to the previous spot—not stay at this location. So we'll test for
that: if we're still at the same location as the last teleport (or close to it), we'll
remove that location from the locs list by using the pop , and set loc to the next
location in the stack.
Either way, we've got a loc pointing to the spot that we want to teleport to.
We'll add the player to the isTeleporting list and teleport the player to the new