Constant Tutorial

You already know about literals. Now, its time to learn how to name them. In the future, this will save you time and make your code easier to read.

Constant Tutorial

Literals, as you learned in the last tutorial, is the fundamental way of getting data into your game. However, dealing with literals can be a pain sometimes if they are long or complicated. Take this printed literal :

print "My wonderful and absolutely perfect game."

This string literal by itself isn't much of a hassle, but what if you had to type it over and over and over in your game code? To save time, we use constants.

Constants Save Your Fingers

Constants are simply a name for a literal piece of data, for example, your game title. Let's assume that we are using the long game title above. First, we need to let FreeBASIC know that we want to give the literal a name. For this, we use const.

const

Then, we give a name to the constant.

const gameTitle

gameTitle is perfect because it is easy to remember and tells you exactly what the constant contains.

Now, we tell FreeBASIC what literal we want to attach to the name gameTitle.

const gameTitle = "My wonderful and absolutely perfect game."

That's it. Now we can use the name gameTitle instead of that long block of text :

const gameTitle = "My wonderful and absolutely perfect game."
print gameTitle
sleep
end

Real-World Examples

You should only have to type your game title no more than once or twice in a game. In actual game code, you will probably be using constants to make numeric literals easier to remember and type. Some things use hexadecimal number literals (a type of literal in hexadecimal base) and constants are perfect to keep them from becoming a headache.

If you have done any web design, you are already familiar with hexadecimal numbers to some extent. You will have used them as colors, like this :

#000000
#FFFFFF

The first is the hexadecimal number for black, and the second is white. The above form is how you would use them in HTML. However, in FreeBASIC, you replace the # with &h.

&h000000
&hFFFFFF

In their current form, they are ugly and hard to understand. Using constants makes everything clear.

const black = &h000000
const white = &hFFFFFF
const red = &hFF0000
const blue = &h00FF00
const green = &h0000FF

Now, when you need to refer to any of these colors, you can use the constant name instead.

A Last Word About Constants

Constants are called constants because their value never changes. After you have assigned a literal to a constant, the value will remain constant (never changing) throughout your game. Later, you will learn about variables. You guessed it. Variables are called variables because their value can change, or vary.

page_revision: 1, last_edited: 1208854154|%e %b %Y, %H:%M %Z (%O ago)