Variable Guide

Variables in Game Programming

Variables hold information (data) about your game and the game objects in it. Things like a character's name or hit points. Anytime you need you need to reserve computer memory to store a single number or single piece of text, you will store them in a variable.

' Example in FreeBASIC
dim pname as string
pname = "Soliztan Margot"
print pname

Declaration of Variables

DIM is used to declare a variable. This associates the identifier with a memory location. In layman's terms, it is simply creating a variable to hold stuff.

Implicit Declaration

Many programming languages allow you to ''implicitly'' declare variables, that is, to have them created during the first time they are used. For example, when you use the assignment operator without first declaring a variable, it is created when this code is run :

location = "The Grim Hall"

Explicit Declaration

Some programming languages force you to ''explicitly'' declare variables, that is, to create them before you use them. This is done with DIM.

' FreeBASIC Example
dim location as string
location = "The Grim Hall"

Explicit declaration of variables is usually done at the beginning of your game code.

Explicit and Implicit Declaration

Some programming languages expect you to use implicit declaration by default (especially modern BASICs) and allow you to explicitly declare variables as you so choose. Most of these languages, such as FreeBASIC and Brutus2D allow you to force the explicit declaration of variables if you so choose. In that case, OPTION EXPLICIT can be used.

If OPTION EXPLICIT is used, then any variable not explicitly declared will result in an error. This saves bugs from misspellings because if you misspell the variable's name, OPTION EXPLICIT will cause an error because the misspelling has not been explicitly declared.

Data Type

The "data" stored in variables usually has to be of a specific type. The most common data types are strings and numbers.

String variables are used for holding messages and other things dealing with ''text''.

Numeric variables are used for math-related operations such as hit points.

Swapping Variable Values

If you want to swap (or switch) the value of two variables, you will need one more variable as a "buffer". First, here's the wrong way to do it :

var1 = 1
var2 = 2
var1 = var2
var2 = var1

This will result in var1 and var2 having the same value (2). The value in var1 was overwritten in line 3. So, to make this work properly, you must store the value of var1 in a kind of variable "buffer".

var1 = 1
var2 = 2
varb = var1
var1 = var2
var2 = varb

This will accomplish the task of switching two variable's values.

Specialized Uses for Variables

These variables are the same as all other variables. These are specific uses for variables.

Related Pages

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution 2.5 License.