Chapter V: Loops

Often, you want to perform actions on a lot of players or modify a series of maps. It would be a Copy and Paste nightmare to write code to affect each player or map. That's where loops come in. Loops allow you to repeat an action any number of times with slightly different variables each time.

For... Next Loops

The most common type of loop is the For... Next loop. The For loop allows you to specify how many repetitions you want. Let's go to the code:

Dim i as Long

For i = 1 To 70
   PlayerWarp(i, 1, 5, 5)
Next i

The PlayerWarp function looks like this in MBSC.inc:

EXTERNAL SUB PlayerWarp(Player AS LONG, Map AS LONG, X AS LONG, Y AS LONG) = 37

PlayerWarp takes the Player you want to warp, along with the destination Map, X, and Y, and warps the player there.

The script above runs the code between the For and Next 70 times, starting with i = 1 and incrementing the variable i by 1 each time. This script will warp players numbered 1 through 70 (essentially everyone) to [Map: 1, X: 5, Y: 5].

While... Wend Loops

The While... Wend loop is less common than the For loop, but there are cases where it is more useful.

Let's write a leveling script. We want to give a player experience until they reach the target level:

Dim TargetLevel as Long

TargetLevel = 255
While GetPlayerLevel(Player) < TargetLevel
   GivePlayerExp(Player, 50000)
Wend

As long as the Player has not reached TargetLevel, the script continues to GivePlayerExp.

A word of warning: sometimes While loops with badly written conditions or other small mistakes enter infinite loops, freezing the server.

« Back to Chapter IV: Variables
Table of Contents
Forward to Chapter VI: Functions and Subroutines »
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.
Hosted by www.Geocities.ws

1