Upcoming Events
Unite 2010
11/10 - 11/12 @ Montréal, Canada

GDC China
12/5 - 12/7 @ Shanghai, China

Asia Game Show 2010
12/24 - 12/27  

GDC 2011
2/28 - 3/4 @ San Francisco, CA

More events...
Quick Stats
96 people currently visiting GDNet.
2406 articles in the reference section.

Help us fight cancer!
Join SETI Team GDNet!
Link to us Events 4 Gamers
Intel sponsors gamedev.net search:

  Contents

 First Requirement
 If Statements
 Loops
 More Theory

 Printable version

 


  The Series

 Storing/Reading
 Doing Something
 Control Structures

 

Loops

Now that we have our first big feat out of the way, the If statement, we can move on to some basic loops. In many ways, looping is actually easier than the If statement that we just learned. So if you got through that last page okay, you will be just fine from here-on-out! :)

For Loops

The for loop is one of the most often-used loops in VB for games, so we'll start with that. Basically, all that you want it to do is execute a command block a specified number of times. Here is a basic implementation of a simple For loop:

Public Function ExecuteCmdFor(a() As String) As Integer Dim i As Integer, b(0) As String 'i will be our counter, b() is a 'placeholder' b(0) = a(1) 'put the name of the command block to be executed 'in b() For i = 0 To CInt(a(0)) - 1 'Use vb's built-in for loop to go from 0 to the 'first parameter, a(0) ExecuteCmdExecuteBlock b() 'execute the block! Next i ExecuteCmdFor = 1 End Function

Simple, huh? Basically, this function becomes a 'wrapper' for vb's native For loop, making life simple on you, the coder. One thing to be noticed, though, is that the command block has no way of knowing the contents of the 'counter' variable, i. Implementing this is something that you should try as an exercise. I would suggest waiting on this, though, until I discuss later possible methods of implementing true, named variables.

Do...Loop Until Loops

This type of loop is also quite simple to implement, again 'wrapping' vb's built-in loop of the same name. Look this code over:

Public Function ExecuteCmdDo(a() As String) As Integer Dim b(1) As String, c(0) As String 'as usual, some placeholder-type arrays b(0) = a(1) b(1) = a(2) 'the b() array will be used for getting the flag c(0) = a(0) 'the c() array will be used for calling the command block Do 'VB's built-in Do command... ExecuteCmdExecuteBlock c() 'execute the command block Loop Until CStr(ExecuteCmdGetFlag(b())) = a(3) 'Loop until bit a(2) of flag a(1) becomes set to a(3) (0 or 1). ExecuteCmdDo = 1 End Function

Again, this function should be fairly straightforward. The only 'new' thing is the ability for the script to specify whether to check for the flag being "on" (1) or "off" (0) as the fourth parameter, a(3).


Next : More Theory