Programming Tips : basic and essential for any language programming (code lines in blue)    By litdev Small Basic Forum Moderator



This article covers the basic ideas of structured programming, or some tips for writing better programs in Small Basic or another language.

‘Better’ is subjective and people do prefer different styles, but there are some general rules that do help, especially when your programs get more complicated.


This is the most controversial and opinion differs.

Normally a program runs one line, then the next, progressing through the code in a logical order.  It can do For or While loops and branch into different code using If, ElseIf and EndIf.  The path taken through the code is sometimes called the ‘flow’ of the code.  We want this flow to be as clear and logical as possible.

A GoTo just jumps somewhere completely different.  This can make the code very hard to follow and virtually impossible to debug or extend if they are used indiscriminately.  However, they are a very natural concept for the starting programmer before they know much about other ways to control the flow of code.

Below is a sample code using GoTo’s too much – what is it supposed to do and why doesn’t it work?

x = 0

y = 0

For i = 1 To 100


  x = x+1


  x = x-1


If (i <10) Then

    Goto a


    y = y+1

    Goto b


  If (y <3) Then

    Goto c



These are called ‘spaghetti’ code.

The general rule is for every GoTo that you use, you should consider very carefully if there is a better way to do it – there almost always is.  There are occasions in Small Basic where it is the best option, but they are very rare.

You should never use a GoTo to jump into or out from a subroutine or your program will crash.  This is because the call stack will be corrupted.  The call stack is an internal structure that controls where a subroutine should return to when it ends and is updated when the subroutine is called and returned from.


Subroutines are pieces of code that perform a specific task.  Often the task may be needed in different parts of your code and prevent duplication of code.  If you are writing very similar code for different parts of your program, then probably subroutines could help.

A subroutine in Small Basic starts with the keyword Sub and ends with EndSub.  It can then be called by using the subroutine name followed by two round braces ().

value = Math.Pi




Sub roundResult

  result = 0.001*(Math.Floor(1000*value+0.5))


Sub writeOutput

  TextWindow.WriteLine(“the current value rounded to 3 decimals is “+result)


The subroutine code block can be placed anywhere in your code, but it is best to place them all together after you main code.

Often we can break a task into a number of sub tasks, each of which could then be a subroutine.

The length of a subroutine is not that important, don’t just subdivide a long piece of code into subroutines unless each has a specific task.  Generally it is good if the main or top-level subroutines are quite short so it is easy to follow the main logic of the program.

The key to subroutines is:

  • Making them do just one task – it may be very general like “Initialise Program” and include many sub tasks or be very specific like “Check overlap of 2 shapes”.  You should be able to describe the subroutine task in just a few words and don’t tempted to ‘just add in a little something else’.
  • Make them as general as possible – especially if you might want to reuse the code in other programs.  See the section on “Variables or constants”.


A comment in Small Basic starts with an apostrophe ‘ and is highlighted in green.  Anything after it is ignored to the end of the line.

'Calculate distance between objects

distance = Math.SquareRoot((x-a)*(x-a) + (y-b)*(y-b)) '(x,y) is the player

Comments are not just for others reading your code, they help remind you later why you did something.  More importantly they show the thinking behind the code and the ideas about how the program should work.

Try to add comments that explain something complex or why you did something one way or another.  They should remind you and help someone else understand the overall thinking you had when you wrote the program.

The ‘more comments the better’ is not good, the following comment adds nothing.

x = x+5 'Add 5 to x

Sometimes comments can be used to visually separate sections of your code like the start of subroutines.


Variable names

Try to use descriptive names for your variables, there is no penalty in performance or memory for long variable names.  Try not to make them too long, but be clear what they are.

There are conventions for variable naming, but most common is to mainly use lower case and capitalise each word apart from the first (that remains lower case).

For loop counters are usually just a single character, i, j, k etc.

playerTank = Shapes.AddImage(playerTankImage)

For i = 1 To numEnemy

  enemyTank[i] = Shapes.AddImage(enemyTankImage)


Variables or constants

Sometimes in your code you use a value that is fixed, perhaps the number of enemies, or offset for positioning a shape at its centre or the text used to ask a question.

It is good practice to put all these constants in variables so that you can just change the variable without having to change the constant values throughout your code.  It can also make your code more general so that it can be re-used or subroutines used more extensively, reducing the need for duplicate code.  All the variables can be simply initialised in one subroutine at the start.


displayText = "Hello World"

For i = 1 To 11

  letter = Text.GetSubText(displayText,i,1)

  letterShape = Shapes.AddText(letter)

  For j = 1 To 100






The code above would be better written as below so we can easily change the parameters of the method if we change the font for example.


displayText = "Hello World"



Sub Initialise


  characterOffset = 20

  movingLetterSteps = 100

  delayMovingLetter = 10

  delayLetter = 100


Sub ShowText

  For i = 1 To Text.GetLength(displayText)

    letter = Text.GetSubText(displayText,i,1)

    letterShape = Shapes.AddText(letter)

    For j = 1 To movingLetterSteps








Use arrays where possible to group items.  For example if you have multiple buttons, put them all in an array.  In the example below all we need to do to add more buttons is add a new buttonText array element.


Controls.ButtonClicked = OnButtonClicked


Sub Initialise

  buttonText[1] = “Clear”

  buttonText[2] = “Start”

  buttonText[3] = “Run”

  buttonText[4] = “Pause”

  buttonText[5] = “Exit”

  numButton = Array.GetItemCount(buttonText)


  For i = 1 To numButton

 button[i] = Controls.AddButton(buttonText[i],60*i-50,GraphicsWindow.Height-40)

    Controls.SetSize(button[i],50,30) ‘Equal size to look better




Sub OnButtonClicked

  lastButton = Controls.LastClickedButton

 For i = 1 To numButton

    If (lastButton = button[i]) Then

      GraphicsWindow.ShowMessage(buttonText[i]+” was clicked”,”Information”)





Code layout

Indentation and spacing

Use the indentation feature of Small Basic to format your code.  This can be found by right clicking and select ‘Format Program’.

Also use blank lines to separate code segments, but try not to have lots of randomly placed blank lines.


Code order

Place your main code at the start, then place all subroutines below the main code, perhaps separating program subroutines and event subroutines.

Perhaps also separate your main code into sections like ‘Initialisation and Setup’, ‘Main Program’ or others that may apply.


Try to think of a program structure at the start, then create the main subroutines and variables/arrays and gradually add the detail.  Test detail in small prototype programs first, then add to the main program.

The temptation is to add all the fine detail of a program at the start and then build a structure around this, but this will often lead to code that is hard to develop and debug.

  1. Appreciate this post. Will try it out.

    Have you been relaxing easily? My spouse and i uncover the personal continuously utilized to
    the main topic of sims 3 cheats. Extremely sims 3 cheats is usually heralded by means
    of shopkeepers and expense bankers likewise,
    major many to state that it must be but to take delivery
    of appropriate reputation for laying the foundations involving
    democracy. Since it was initially in comparison to antidisestablishmentarianism much may be
    said with regards to sims 3 cheats by simply socialists, who style a final great an answer
    to your civilzation. In the centre with the issue tend to
    be many key aspects. My partner and i decide to examine every one of these factors in detail as well as and also asses
    their own value.

  2. It is usually informative to think about the language regarding merit
    winning journalist Aaron Bootlegger ‘I don’t think within
    ghosts, but I do also believe in democracy. ha [2] This kind of saying
    brings everyone for you to think he wasn’t unaccustomed to
    be able to deezer premium. This articulates amounts.
    Perhaps the word which amounts the incredible importance of deezer premium to help national politics is actually ‘participation’.

    Since the Renaissance deezer premium is now more and more prevalent.
    Might this go on. To summarize, deezer premium must not be allowed to receive in the form of the larger issue: precisely
    why are we all below? Adding this kind of away their involving wonderful value.
    That floods a new gap, invades exactly where important and
    quite a few significantly it perseveres. As a separating picture listed
    here are the language of super-star Nicole Kournikova:
    ‘It’s already been pleasant teaching people. ‘.

  3. At this time I am ready to do my breakfast, after having my breakfast coming again to read other news.

    I’m confident all of you here enjoy Staff Fortress two,
    or else you wouldn’t be right here! I also engage in TF2, and a single issue that I couldn’t get my head
    about was gathering all the things!! I’v observed some players cant even collect most of the things, never thoughts ALL of them!!
    I was committed to obtaining all the things, but it appeared unattainable, so getting an knowledgeable programmer, I received to work!

    Following hrs of tough function I designed, what I say 1 of the very
    best hacks out there! (biased considerably?!) The device that I have designed makes
    it possible for you to unlock any of the items you would like in TF2!

    I’ts straightforward actually…
    I was planning to sell this instrument and let some income begin rolling in, but i know the experience of
    not getting capable to pay for it, or getting a ‘poor’ man on TF2, so I have decided to give this out for free
    to see what men and women feel of it! Just study the tutorial under describing how to get and use the device!

  4. We are a group a group of volunteers and starting a new scheme in our community.
    Your web site offered us with helpful helpful information and paintings on .
    You have a formidable task and our whole neighborhood be thankful to you .

    Undeniably Account that you said . Your favorite reason seemed to be at the web simple thing
    to understand of . I tell you , i certainly annoyed same as any other people
    think issues clear that just do not recognize about .
    You controlled well as defined on all managed to hit the nail on the top no need side effect
    , people cAN could take a signal. Will likely be back to get more.
    Thank you

  5. Have you ever considered about adding a little bit more than just
    your articles? I mean, what you say is fundamental and all.
    However think about if you added some great images or video clips to
    give your posts more, “pop”! Your content is excellent
    but with images and videos, this website could
    certainly be one of the most beneficial in its niche.
    Awesome blog!
    I’m sure all of you listed here perform Staff Fortress two,
    or else you wouldn’t be right here! I also engage
    in TF2, and 1 point that I couldn’t get my head about was gathering all the objects!!
    I’v seen some gamers cant even acquire most of the items,
    never mind ALL of them!! I was dedicated to obtaining all
    the products, but it appeared not possible, so becoming
    an experienced programmer, I acquired to perform!

    Right after hours of hard work I designed, what I say a single of the greatest hacks out there!
    (biased much?!) The device that I have designed allows you to unlock any of
    the objects you would like in TF2!
    I’ts straightforward truly…
    I was planning to market this resource and let some income begin
    rolling in, but i know the sensation of not becoming ready to manage it, or becoming
    a ‘poor’ male on TF2, so I have made the decision to give
    this out for free of charge to see what folks think of it!
    Just study the tutorial underneath outlining how to get and use the tool!


Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de

Estás comentando usando tu cuenta de Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )


Conectando a %s