Hello World

From SolarStrike wiki
Jump to: navigation, search

Intro

In this tutorial, we will create a script that prints the text "Hello World!" to the screen, then asks the user to press the space bar to terminate the script. We will be using printf(), startMacro(), and keyPressedLocal() to accomplish this.


The setup

The very first thing you will do when starting a new script is insert your main function, and call startMacro(). These are not entirely necessary, but make things much easier for us later on because they allow for things such as automatic start/stop keys, automatic timers, and run everything in a protected environment. Your main function can be named anything, but most people just use "main". So lets start with setting that up.

-- This declares our "main" function which will contain our "main loop".
function main()

end


-- startMacro will now call main() within a protected environment for us.
startMacro(main);


The main loop

A "main loop" is simply a loop structure (typically a "while" statement) that is run for the duration of your program. That is, the main loop repeats itself over and over until the script should terminate. In this example, we will use a "while" statement to check if the user has pressed a key. Using a 1 inside of while() means that it will keep looping indefinitely. We will check manually inside the loop and use "break" to exit from the while.

Remember, keyPressedLocal() accepts a virtual key, and tells us if that key is pressed. We will be using this to check if the space bar has been pressed or held down.

-- This declares our "main" function which will contain our "main loop".
function main()

  while(1) do
    -- if they press space bar, break out of the while
    if( keyPressedLocal(key.VK_SPACE) ) then
      break;
    end
  end

end


-- startMacro will now call main() within a protected environment for us.
startMacro(main);


Printing text

Now we just need to inform the user what is going on. One of the most handy functions for this is printf(). It allows us to use special tags to replace text, however, we will be using it in it's most simple form. You will note that we are adding a "\n" at the end of the text we want to show the user. The "\n" will not be visible; it simply means to go down a line.

-- This declares our "main" function which will contain our "main loop".
function main()
  printf("Hello World!\n");
  printf("Press SPACE BAR to terminate script.\n");

  while(1) do
    -- if they press space bar, break out of the while
    if( keyPressedLocal(key.VK_SPACE) ) then
      break;
    end
  end

  printf("Goodbye!\n");

end


-- startMacro will now call main() within a protected environment for us.
startMacro(main);

And there you have it. If you save this script into your scripts directory and run it, you will see it says "Hello World!" then asks you to press the space bar. Once you press the space bar, it will say "Goodbye!" and the script ends.