Chapter IV: Variables

Storing Data

Often you need to store data so you can use it later. For example, you may want to do several mathematical calculations on it, or use it in multiple places. Variables allow you to store data for later use.

You can create a variable by using a Dim statement. This is called declaring the variable.

Dim number as Long

Variable names can only contain alphanumeric characters (A~Z and 0~9) and the underscore character (_) and must start with a letter.

You can assign a value to a variable using the assignment operator (=).

Dim number as Long
Dim message as String
number = 524
message = "Cowguins can fly."

number now contains the number 524 and message now contains the text "Cowguins can fly."

Variable Types

MBSL differentiates between two types of variables: LONGs and STRINGs. Long is short for long integer. Longs are used to store and manipulate integers. (MBSL has no decimal or floating-point math.) Strings are strings of characters. They are used to store text.

The following code snippet highlights the differences between Longs and Strings:

Dim num as Long
Dim text as String
num = 53 + 82
text = "53" + "82"

num now contains the number 135, while text now contains the text "5382".

Parameters

Let's go back to PlayerMessage for a moment. If you look in MBSC.inc, you'll see it defined there, just like the colors were defined in Chapter 2:

EXTERNAL SUB PlayerMessage(Player AS LONG, Message AS STRING, MsgColor AS LONG) = 36

The PlayerMessage function takes three parameters, Player, Message, and MsgColor, which as you may have guessed, are variables! Player refers to the player number of the player you want to message and is therefore a Long and Message is, of course, a String. MsgColor is a Long; however, MBSC.inc has defined 16 constant variables that you can use instead of the numbers 0~15. For parameters, you replace the variables there with your own variables or literals, like "Hello."

Type Conversion

But if variable types are separate, how would I perform mathematical calculations and then output the results to a player using PlayerMessage, which takes Message as String?

Fortunately, MBSC.inc contains two built-in functions that let you convert between Longs and Strings:

EXTERNAL FUNCTION Str(Value AS LONG) AS STRING = 56
EXTERNAL FUNCTION Val(St1 AS STRING) AS LONG = 94

They can be used like this:

Dim var as Long

var = GetPlayerAccess(Player)
PlayerMessage(Player, "Your class number is " + Str(GetPlayerClass(Player)) + ".", BrightBlue)
PlayerMessage(Player, "Your god access level is " + Str(var) + ".", BrightBlue)

The Longs in var and returned by GetPlayerClass are converted to Strings using Str and can be used in the Message AS STRING parameter.

« Back to Chapter III: Conditionals
Table of Contents
Forward to Chapter V: Loops »
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.
Hosted by www.Geocities.ws

1