Small basic language tutorial – programming is fun!

Introduction

It was probably in 1989 that I got a chance to work with computers. Our school had one of those machines (don’t remember what it was!) which came with pre-installed BASIC interpreter. Two things stand out in my mind – it had a color display and I could program games in it! From the very first day I was hooked on to computers thanks to the power and the fun offered by BASIC language. Later we (me and my brother) ended up creating some fairly sophisticated games using QuickBasic compiler.

However once I got a job all these hobbies went in the background and I was programming in Java from the beginning. Once in a while I used to read our old basic programs which brought back the memories of fun we had with the language. Unfortunately BASIC compilers were no longer bundled with Windows and the only way to have fun with the language was to install a DOS emulator such as DosBox. I resented Microsoft’s decision to remove BASIC language from their Windows products.

Then in October 2008, Vijaye Raji (a Microsoft engineer at that time) came out with a scaled down version of Basic language called Small Basic. It had brought back the fun and the hobby of programming!

Small basic is suitable for introducing a programming language to kids. It is also a hobbyist language since you can quickly create powerful programs using it. If you already know programming, it takes just an hour to learn the language!

History of Small Basic

In 2006, Salon carried an article titled “Why Johnny Can’t Code?”. According to the author (David Brin), kids today had no easy way to learn about programming. We had BASIC during our childhood days and today’s kids had C++ and Java which was tough to learn. Also BASIC was synonymous with FUN!

It is this article which prompted Vijay Raji to think about creating a scaled down version of BASIC language which would help kids to learn about programming. He wanted to provide 3 things out of the box,

  • A good development environment which is easy to use
  • A simplified BASIC language with minimal set of keywords
  • A simple yet powerful API to make programming fun!

Initial release of Small Basic (0.1) was in October 2008 and Small Basic 1.0 was released in 2011. Small Basic 1.0 supports 20 languages.

Small Basic Pre-requisites

Small Basic can be installed on Windows XP, Windows Vista or Windows 7. It requires .NET framework 3.5 to be installed on your system. Windows 7 contains .NET framework and for Windows XP, you can download it from here.

Installing Small Basic is easy. Download the installer file (SmallBasic.msi) from the official Microsoft page for Small Basic. The whole package including compiler, IDE and the API is only 6 MB! During installation, you can choose the preferred language for Small Basic. As version 1.0, Small Basic supports 20 languages. Click on the installed icon to get the simple yet very functional IDE for small basic,

Small Basic IDE

The small basic IDE is composed of 3 panes. The top pane is the toolbar, the left pane is the editor and the right pane shows context sensitive API documentation. Also note the cool intelli-sense window overlapping the editor window. If you press “Control” key while the intelli-sense popup is shown, it becomes semi transparent. Try it!

Small basic IDE toolbar is simple and easy to use and contains the following features,

  • File – Create a new small basic program, save or open a small basic program
  • Web – You can now publish your small basic programs to the cloud! The program is uploaded to www.smallbasic.com and you can run on a browser if silverlight is installed. It is also possible to open a program already published on www.smallbasic.com from the small basic IDE.
  • Clipboard – Standard copy/paste operations.
  • Program - You can run the program or convert your program to visual basic. For  beginners in programming, it gives a roadmap to Microsoft visual studio express and visual basic.

When you run a Small basic program, it is first compiled into a .NET program. This .NET program requires .NET framework 3.5 installed on your system to work.

Small Basic Language Fundamentals

Small basic is an imperative language with a very small set of keywords (14 in total). It has a dynamic type system, uses procedural paradigm, supports events and has no support for objects.

What makes small basic unique is that even though language itself has no support for objects, it can make use of external libraries with a construct similar to object method invocation! Hence these external libraries cannot be written in small basic.

The small basic language is so simple that there is no formal specification document for it!(in fact I couldn’t find one) Small basic is very similar to BASIC language. The fundamental language features are (most of them are similar to qbasic or quickbasic),

  • Keywords and variables are case insensitive in small basic.
  • Use single quote prefix for comments.
  • Small basic has only global variables. There are no subroutine parameters or local variables.
  • Small basic uses dynamic type system. Variables are never declared and you can assign any value to variables.

Small Basic Quick Tutorial

Small basic programs are executed from the first line of the program. To comment a line, start the line with a single quote.

Variables

Small basic only supports global variables. Variable name should start with a letter and can contain letters, digits and underscores. Variables has no type and need not be declared. A keyword cannot be used as a variable.

Conditional Execution and Branching

Use if, then, else, elseif and endif keywords for conditional execution. You can use goto for branching. A line of code can be labeled using a token suffixed with colon. Here is an example,

value = 90
If(value > 50) then
  TextWindow.WriteLine("greater than 50")
Else
  Goto end
EndIf
TextWindow.WriteLine("difference from 50 is " + (value - 50))
end:

Loops

for, to, step, while and endwhile are looping constructs in small basic. Here is sample for loop which is executed from 0 to 100 and step indicates the increment after each iteration. Hence this loop is executed 10 times.

For i=0 To 100 Step 10
  TextWindow.WriteLine(i)
EndFor

Subroutines

Subroutines allows us to group a repeating part of code. It enables code reuse. In small basic, subroutines doesn’t support parameters or return values.

a=10
b=20
Add()
TextWindow.WriteLine(sum)
 
Sub Add
  sum = a+b
EndSub

Arrays

Array is a special variable in small basic which can hold more than one value at a time. The values in the array can be accessed using an index or using a key (associative array). Multidimensional arrays are also supported in small basic.

'associate array
val["name"] = "jayson"
val["city"] = "trivandrum"
TextWindow.WriteLine(val["name"])
'indexed array
val[0] = "test"
val[1]= "another test"
TextWindow.WriteLine(val[0])

Events

In small basic, API objects can have event handlers. You can pass subroutine names in your code as values for the event handlers and when the event is triggered, your subroutine code is invoked. For example, Timer object has a tick event to which you can add a subroutine. It will be invoked for every tick of the timer.

' play bell every 5 seconds
Timer.Interval=5000
Timer.Tick = CreateSound
Sub CreateSound
  Sound.PlayBellRing()
EndSub

Please also refer to the official getting started guide.

Small Basic Keywords

Small basic has a very small set of keywords,

if else elseif endif for endfor
sub endsub while endwhile then goto
step to

 

Overview of Small Basic Library API

It is interesting that even though small basic doesn’t support object oriented programming, It can call static class methods (and object properties!) written in any .NET language (subject to a number of constraints). The default library provided with the language is powerful enough to do a lot of interesting things with the language. The following is an overview of the API library which is composed of 19 singleton objects,

Object What it does Sample code
Array Use this object to manipulate associative arrays in small basic
' create a simple array
For i=0 To 10
  ar1[i]=i
EndFor
' check whether it contains the value 5
TextWindow.WriteLine(Array.ContainsValue(ar1,5))
Clock Get access to current date and time
'  print date, time 
'  and number of milliseconds elapsed since 1900
TextWindow.WriteLine(Clock.Date)
TextWindow.WriteLine(Clock.Time)
TextWindow.WriteLine(Clock.ElapsedMilliseconds)
Controls Add various form controls to the graphics window
Controls.AddTextBox(50,100)
Controls.AddButton("submit",50,120)
Desktop Get your desktop dimensions and change your wall paper. Changing wall paper is fun! :-)
' Assign a random picture from flickr as wall paper
Desktop.SetWallPaper(Flickr.GetRandomPicture("ocean"))
Dictionary Accesses an online service and returns the dictionary meaning of a word
TextWindow.WriteLine(Dictionary.GetDefinition("help"))
File Provides basic features for reading and writing files  
Flickr Get Flickr photos
' display a random flickr image
img = Flickr.GetRandomPicture("nature")
GraphicsWindow.DrawImage(img,10,10)
GraphicsWindow Use this for drawing. Ideal for writing games!  
ImageList Load images from file or from a url  
Math A small set of common math functions  
Mouse Track mouse position and status  
Network Download pages via http
' Dump google page to graphics window
txt = Network.GetWebPageContents("http://www.google.com")
GraphicsWindow.DrawBoundText(10,10,300,txt)
Program Get command line arguments or pause the program  
Shapes Add, move and rotate various shapes in graphics window
' Simple Animation
x = 0
y = 0
ball = Shapes.AddEllipse(20,20)
Timer.Interval = 20
Timer.Tick = MoveBall
 
Sub MoveBall
  x=x+1
  y=y+1
  Shapes.Move(ball,x,y)
EndSub
Sound Simple sound functions. Also supports qbasic music notes  
Stack Stack data structure  
Text Simple set of string operations  
TextWindow Command line text input/output  
Timer Enables executing a subroutine at fixed intervals
' play bell every 5 seconds
Timer.Interval=5000
Timer.Tick = CreateSound
Sub CreateSound
  Sound.PlayBellRing()
EndSub
Turtle Draw shapes using a pen and a set of commands
' draw a triangle
Turtle.PenUp()
Turtle.MoveTo(300,200)
Turtle.Angle=30
Turtle.PenDown()
Turtle.Move(80)
Turtle.Angle=150
Turtle.Move(80)
Turtle.Angle=270
Turtle.Move(80)

 

Extending Small Basic

Small basic executables are .NET programs and hence can use any type in a .NET assembly written using any .NET language as long as the type meets the following requirements (don’t forget to add SmallBasicLibrary.dll as a project reference!),

  • The type should be declared static.
  • The type should have the attribute (annotation) [SmallBasicType] attribute.
  • The types can support methods and properties. All properties should be of type Microsoft.SmallBasic.Library.Primitive
  • All input and output parameters for methods should be of type Microsoft.SmallBasic.Library.Primitive
  • All events should be of type Microsoft.SmallBasic.Library.SmallBasicCallback

Once you create an assembly meeting all the conditions above, you can copy the dll into the “lib” folder under small basic installation. Usually this is located in “C:\Program Files\Microsoft\Small Basic”. If you need intelli-sense, create and copy the doc xml to the same folder.

Let us create a very simple small basic extension. This extension can return random quotations from a fixed library of quotes. It will have just one method,

QuoteEngine.GetQuote()

Let us create this extension as a library in C# which respects all the rules given above. Here is the code for QuoteEngine type,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SmallBasic.Library;
 
namespace QuoteEngine
{
    [SmallBasicType]
    public static class QuoteEngine
    {
        static String[] quotes = { "Glory is fleeting, but obscurity is forever", 
                                 "Sex and religion are closer to each other than either might prefer",
                                 "The only way to get rid of a temptation is to yield to it",
                                 "The gods too are fond of a joke",
                                 "The cynics are right nine times out of ten",
                                 "Knowledge speaks, but wisdom listens",
                                 "A clever man commits no minor blunders",
                                 "Most people would sooner die than think; in fact, they do so",
                                 "A narcissist is someone better looking than you are",
                                 "Wise men make proverbs, but fools repeat them",
                                 "The difference between pornography and erotica is lighting"};
        public static Primitive GetQuote()
        {
            Random r = new Random();
            int v = r.Next(0, 11);
            return quotes[v];
        }
    }
}

Copy the generated dll file to the lib folder (C:\Program Files\Microsoft\Small Basic\lib). Type in the following small basic program and execute it to see this extension in action!

quote = QuoteEngine.GetQuote()
TextWindow.WriteLine(quote)
quote = QuoteEngine.GetQuote()
TextWindow.WriteLine(quote)

Sample Small Basic Program

Following is a simple game of “bat and ball” written in small basic. The objective of the game is to move the bat using mouse and deflect the ball back into the board. This took me 5 minutes to write (I have hosted this on www.smallbasic.com and you can run it in silverlight enabled browser by clicking this link),

Timer.Interval=10
Timer.Tick = ProcessCycle
bat = Shapes.AddRectangle(60,15)
ball = Shapes.AddEllipse(10,10)
xinc=5
yinc=5
Sub ProcessCycle
  batx = Mouse.MouseX-GraphicsWindow.Left
  Shapes.Move(bat,batx,400)
  ballx = ballx+xinc
  bally = bally+yinc
  Shapes.Move(ball,ballx,bally)
 
  'check collision!
  If(bally > 395) Then
    If(ballx > batx And ballx < batx+60) Then
      yinc = -yinc
    EndIf
  EndIf
 
  If(ballx > GraphicsWindow.Width) Then
    xinc = -xinc
  EndIf
  If(ballx < 0) Then 
    xinc = -xinc
  EndIf
  If(bally < 0) Then
    yinc = -yinc
  EndIf
EndSub

Small Basic FAQ

Is there a way to pass parameters to a subroutine in small basic?

Small basic language doesn’t support parameters in the case of subroutines. In fact the only type of variable supported are the global variables. However it is possible to simulate subroutine parameters using the Stack object as shown below,

Stack.PushValue("p",45)
Stack.PushValue("p",55)
Sum()
TextWindow.WriteLine("Sum is "+ Stack.PopValue("p"))
 
Sub Sum
  Stack.PushValue("p", Stack.PopValue("p")+Stack.PopValue("p"))
EndSub

Videos on Small Basic Language

Intro to small basic

Basics of small basic

Small Basic Web Resources

Click here to get latest site updates delivered to your email. You need to confirm subscription by clicking on the link sent by feedburner to your email address.


July 28, 2011 | Posted in Programming 1 Comment » | By Jayson Joseph

One Comment to “Small basic language tutorial – programming is fun!”

  1. Jerry Collier Says:

    What are the variable limits, max string limit, long integers (as in vb6)?, is there a seek command for file position, what kinds of file I/O. A comparison with vb6 commands, etc. would be most helpful.

    Thanks

Leave a Comment