Hello World Samples

[ LiB ]

Hello World Samples

Now that you've seen snippets and small samples of code, it's time to look at what a fully functioning program looks like in each language.

Programming in each language is explained in depth in each of the following sections, so don't be concerned if the code sample that follows appears foreign. This is just a sample to whet your appetite.

The Python Environment

Python is at home in a number of different environments and can be programmed via command line, script, or debugger. This section will help you install Python on your system and will demonstrate the different options available when you need to sit down and write code.

Installing Python

This book's CD-ROM comes with the tar archive and the Windows installer for Python Version 2.2.2 (released in October of 2002); you can find them in the Python folder. You can also download Python installers for a number of other different platforms from the Python.org Website at http://www.Python.org/download.

As of this writing, Python 2.32 alpha is available from Python.org in Windows. The alpha is also included on the CD, but the samples in this book were written with Version 2.22.

Simply double-clicking on the Python-2.2.2.exe file located on the CD under \PYTHON will run the Windows installer. The installation is fairly straightforward; just click OK on the windows that pop up (see Figure 2.8).

Figure 2.8. The Windows Python Installer in action

graphic/02fig08.gif


If you'll be installing for a UNIX platform, you'll need to perform the regular steps for unzipping the tar archive and installing ( gunzip , tar , ./configure , make , and make install ). You will want to perform this action as root .

If you'll be installing Python on a Macintosh, you will want to use the MacPython222Full.bin file for OS 8.6 or higherexcept for OS X. For OS X, you will want to use the standard tar archive. If you are running Mac OS X 10.2 or later, Python actually ships on the platform, and you won't need to install it at all. Python for the Macintosh is maintained by an independent programmer named Jack Jenson. You can find patches for a few older Mac operating systems and more information at his Website at http://www.cwi.nl/~jack/macpython.html.

If you are running Red Hat and want to grab the RPM sources instead of using the tar, they are available for some distributions from Python.org. Just go to the Website and check out the Download page.

If you do decide to use a version of Python other than 2.2.2, be sure you use Version 2.0 or higher. Python went through a few significant changes from Version 1 to Version 2, and if you use a version earlier than 2.0, you may have trouble running the code samples in this book.

The Python language is copyrighted by Stichting Mathematisch Centrum in Amsterdam. However, it is free to use, copy, modify, and distribute and is OSI ( Open Source Initiative) certified. You can find a copy of the license and copyright in the Python folder on the accompanying CD, and again in the Licenses folder.

NOTE

CAUTION

Intellectual-property attorneys exist for a reason: It is possible to get in legal trou ble selling open-source software. Luckily, the open source community is fairly watchful about intellectual property law, and licenses are becoming somewhat standard and easier to read. There are risks associated with incorporating open source code into commercial endeavors that should not be taken lightly but these risks should not prevent you or your company from using this viable and effective resource. If you have concerns or questions about a license, or about using any open source software in a major enterprise, by all means ask an expert.

Running the Python Interpreter

After you've installed Python on a Windows machine, the Python interpreter is accessible via the run command. Simply do the following:

  1. Open your Start menu.

  2. Select Run.

  3. Type python and hit OK, as illustrated in Figure 2.9.

    Figure 2.9. Windows XP waits for a command from the user to launch Python

    graphic/02fig09.gif


You will get a command window that looks like Figure 2.10 saying:

Figure 2.10. The Python interpreter awaits your command

graphic/02fig10.gif


 Python 2.2.2 <#37, Oct 14 2002, 17:02:34> [MSC 32 bit <Intel>] on win32 Type "help", "copyright", "credits" or "license" for more information >>> 

NOTE

CAUTION

The Python installer tries in good faith to set your machine path variables so that you can run the Python binaries from the command line or anywhere else for that matter, but the installer may not be able to on your particular platform. If you cannot get Python to launch from the command line, you may have to set the path variables yourself or simply run the Python (command-line) entry that is added to the program files listing under Python 2.2.

On a UNIX system, the Python interpreter is usually installed as /usr/local/bin/python, but of course where the interpreter lives is an installation option left up to you. You will need to put /usr/local/bin in your UNIX shell's search path to make it possible to start the interpreter by typing the command python to the shell.

The Python interpreter actually operates somewhat like a UNIX shellit reads and executes commands interactively. The interpreter can also be called with a filename argument or with a file as standard input.

Go ahead and test out the interpreter. You can start by executing various one-liners like print "hello world" or 5*5 . The interpreter is great for testing out certain functions. The interactive help is also very useful. Type the following at the interpreter's prompt:

 >>> help (list) 

You will receive information on the list command, its syntax, and samples of its use (as illustrated in Figure 2.11).

Figure 2.11. Python's interpreter shows how to use the built-in list class object

graphic/02fig11.gif


In this mode, which is called interactive mode , you can type any Python command and it will work just as if you typed it from a script (with a few differences). If you type a command that returns a value of some sort (except assignments), the interpreter will print the result automatically. This is great for experimenting and for testing a specific language feature when you need to get the syntax right. The interpreter isn't very helpful, however, when it comes to large sections of code or actual programs, which you will want to write and then execute at once.

What the interpreter is quite good at, though, is running through the code snippets and short examples you'll find in the next few chapters. You can easily run one-liners to test a particular Python feature, or you can write short, multiple-line code snips by first using a colon and then tabs to delineate a code block (as illustrated in Figure 2.12):

Figure 2.12. The Python interpreter is poised to run this five-line code snippet

graphic/02fig12.gif


To exit Python's interpreter, hit Ctrl-Z on Windows and then press the Enter key, or in UNIX, hit Ctrl-D.

NOTE

TIP

When a script file is used, it is sometimes useful to be able to run the script and enter into interactive mode after wards. You can do this by passing the -i (i is short for "interactive") argument to the script.

NOTE

TIP

When you use Python interactively, you can set standard commands to execute every time the interpreter is started. You can do this by setting the environment variable PYTHONSTARTUP to the name of a file containing the commands (this is similar to the .profile feature in UNIX). This file is only read in interactive sessions, not when Python reads commands from a script.

Creating Python Program Files

You can also run Python programs from a file. The usual extension for a Python program is .py. To create new Python program file, just fire up your favorite text editor, type in a few commands, and save the program as something .py. For instance, on Windows, open up Notepad and type in:

 print "Hello, World!" 

and save the file as hello.py. You can then save the file to disk, open up your command line, browse to hello.py, and run it, as shown in Figure 2.13.

Figure 2.13. A Python program file runs on Windows

graphic/02fig13.gif


You can create Python program files on other operating systems just as easily, except that in a Posix environment (UNIX or Linux), you will need to include a line at the top of each file that points to where Python is installed on your system, like this:

 #!/usr/local/bin/python 

This makes the file directly executable, like any other shell script.

Python's "Hello World"

A Python "Hello World" looks like this:

 #!/usr/bin/python ############ # HELLO_PYTHON_1.py # This program displays the string "hello" . # It first shows the path to python, then creates a short loop, and then prints the string. ############ while (1) :          print "Hello!"; 

Most of this script is made up of comments. Python ignores lines that start with the # symbol, so coders can place their comments and notes in the source code. The one exception to this (and you will find that there are few exceptions in Python) is the very first line of code in this sample. The #!/usr/bin/python command lists the path to the Python program files so that when the script is run, the computer knows where Python resides. This line is optional in Windows, but is normally required when running on a UNIX environment, and so it is included here.

Following the path and the comments is a short while loop. This line says, "Do whatever follows once." Then the print instruction follows. Notice that the print line is offset , or tabbed inwards. White space in Python actually serves a purpose; it places the print command within the jurisdiction of the while loop. Also notice the semicolon at the end of that line. Semicolons, as you've learned, are used to end a statement.

This source code can be found in the \CHAPTER2 folder on the accompanying CD. If you run the program, you will see "Hello!" printed to the screen.

C's "Hello World"

For comparison, let's see what Hello from C would look like. There are many different ways to get C to print a string, but typically the effort looks like the following:

 ############ # HELLO_C_1.cpp # This program displays the string "hello!". # It first Includes the stdio.h library, then creates a main, # then creates a short loop, and then prints the string.  ############ #include <stdio.h> main() {   for(;;)       {           printf ("Hello!\n");       } } 

The comments are the same as in Python, but besides the comments you can see that the program is very different. First, C doesn't have a built-in print function, so you need to import a library that does. stdio.h is short for Standard Input and Output. The library is standard and comes with most C compilers, but it will add a significant amount to the compiled binary.

Second, every C program needs a main statement, a place for the main program piece to run in. This means that main() must be declared before you can proceed any further. Then come the squiggly brackets {}. C uses brackets to separate blocks and section of code. Whatever is in main must be bracketed by squiggly brackets.

Then comes the loop (in this case a for loop), which serves the same purpose here as Python's while loop; the syntax is, of course, different. Again, squiggly brackets are needed to bracket off what belongs within the for loop.

Finally, we get to printf , a command from the stdio.h library that prints input to the screen. Notice that the string must be between both the parentheses () and the quotation marks "". There is also the semicolon (;) that follows the end of a statement, something in common with Python. The \n is actually an escape sequence that creates a new line once the "Hello!" is printed.

The key thing to notice is that with C there are a few extra steps:

  • A library that can work with strings must be imported.

  • There must be a main() .

  • Brackets {} must separate code blocks.

Also look at the syntax. Any missed colon, semicolon, parenthesis, bracket, slash, or pound sign will result in a program error. Python's code has fewer symbolic syntax needs because the designers wanted something that would be easy to write and read.

The Lua Environment

The idea behind Lua is that it is to be used as a lightweight configuration language for any program that needs one. It is written in clean C, which means the Lua source code is made up of the most common subset of ANSI C and C++. Since this section is about Lua and this book isn't a book on C, I won't spend a lot of time going over any C code. If you want a primer on the C language, I suggest picking up a book on C; there are hundreds to choose from.

Lua is implemented as its own library. It's purely an extension language, and so it has no "main" loop of its own. Lua normally functions embedded within a host client, like C code or a C program. It is the host program that invokes Lua code, reads and writes Lua variables, and so on. Lua can also be extended by C and C functions. We'll look more at combining Lua and C (and Lua's C API) in the next chapter, and we'll examine extending Lua, Python, and Ruby in Chapter 12.

The use of C in this book is actually pretty infrequent. In fact, all the code samples in this chapter should run fine in the Lua interpreter alone. If you come across something in C that doesn't make sense, don't get nervous; just move on. Eventually, all code will succumb to your will and prowess.

Normally Lua is used within a host language, and usually the host language is C. Lua can also be used alone, usually for quick glue programs or text-processing utilities. These standalone projects tend to rely heavily on the basic libraries Lua provides. Finally, there are applications that use Lua as a library. These apps tend to have more program code in C than in Lua, and they create interfaces to the Lua language within C.

In this chapter, almost all of the examples are pure Lua and can be run with the Lua interpreter. Using Lua within a host language or library is covered more in the next chapter, where I get down to using Lua in a game-programming environment, and also in Chapter 12, where I'll discuss extending and embedding high-level languages.

Installing Lua

Lua is free software, and the license is included in the CD folder (under Lua) along with the necessary packages for building and installing Lua 5.0. This includes a generic tar.gz for building Lua from scratch on most platforms and an .rpm (Redhat Package Manager) for Linux Red Hat. You can build Lua from the source on any UNIX-flavor machine with the provided make files.

In order to build Lua from the source on a Windows machine, you need a development environment like Visual C++ 6.0 or Cygwin, but luckily for you, the precompiled win32 executables and binaries are included in the LuaWin32.zip file. Instead of your building Lua from scratch, the zip file will provide a lua.exe executable that starts up the Lua Interpreter.

NOTE

CAUTION

The preconfigured lua.exe and luac.exe binaries are statically linked, so when devel oping real projects you will want to place these within the bin folder of the full Lua source tree. The libraries included should also be placed in the Lua lib folder so that they can link with one another. See the doc umentation on installing Lua at http://www.lua.org

Lua 5.0 was released in April 2003. Some new features in 5.0 include:

  • Coroutines (collaborative multi-threading )

  • Full lexical scoping ( replaces upvalues)

  • Metatables (replaces tags and tag methods )

  • Support for true / false Booleans

  • Weak tables

  • New API methods

  • New error handling techniques

The original Lua language (Version 1.1) was first publicly released in 1994. Way back then, the language was free for academic use, but commercial licenses had to be negotiated. However, no commercial negotiations ever occurred, and in Feb 1995, with Version 2.1, the license opened up to commercial use. For the most recent version of Lua, check with the Lua home page at http://www.lua.org.

Or with Tecgraf at http://www.tecgraf.puc-rio.br/.

Lua was designed to run on anything out of the box. This versatility is a result of its plain vanilla C; you just need an ANSI C compiler to compile it. Lua should run not only on all standard Windows platforms, but also on UNIX, Linux, Solaris, SunOS, AIX, ULTRIX, and IRIX, not to mention NextStep, OS/2, Sony Playstation, Macs, BeOS, MS-DOS, OS-9, OSX, EPOC, and the PalmOS. Whew! Again, all you need is an ANSI C compiler to build Lua on the given platform.

The Lua Interpreter

The standalone interpreter (lua.exe on Windows machines) that comes with Lua is extremely useful, as it runs an interactive mode. When fired up, the interpreter displays the Lua version number and copyright notice at the top of the window, along with a greater than (>) symbol as a prompt (see Figure 2.14).

Figure 2.14. Opening the Lua stand alone interpreter

graphic/02fig14.gif


In the interpreter, each command that you type executes immediately after you press the Enter key, and that line is considered to be a whole Lua chunk (more on Lua chunks in just a bit). The Lua interpreter is fairly smart, and if you need to enter multiple lines (for example, when creating a function), the Lua interpreter doesn't execute right away; instead, you will see two greater than symbols, indicating that the interpreter is waiting for you to end the function before executing (see Figure 2.15).

Figure 2.15. The multiple-line function in the Lua interpreter

graphic/02fig15.gif


Most of the commands and samples in this chapter can be run in the interpreter, which is an excellent tool for getting a feel for Lua. I suggest you keep the interpreter open and try the sample code as you go along in the book.

Creating Lua Program Files

As I said, Lua is normally implemented via its host language. The host calls Lua with a lua_open command and then closes it with a lua_close command. A unit of Lua is stored in a file or string within the host program and is called a chunk . When the host executes a Lua chunk, the chunk is precompiled into bytecode for a virtual machine, and then the statements are executed in a sequential order. This Lua chunk does its thing, perhaps making changes to the global environment (that persist after the chunk ends), and then it ends (see Figure 2.16).

Figure 2.16. Lua being implemented via the C host language

graphic/02fig16.gif


NOTE

The term virtual machine (VM) was coined by Sun Microsystems to describe the runtime environment for their budding Java language. A VM acts as an interface between a compiled binary code and an operating system.

Lua has been designed as an extension language but it can be used as a stand-alone language as well. The Lua interpreter (named lua.exe) can be called via command line to execute Lua files (known by their .lua extension) and accepts a number of arguments, as shown in Table 2.7.

Table 2.7. Lua Interpreter Command-Line Arguments

Argument

Purpose

-

Executes stdin as a file

-e stat

Executes string stat

-f file

Requires file

-i

Enters interactive mode after running script

-v

Prints the version information

--

Stops handling options


If the Lua interpreter is given no arguments, it behaves as if lua - , or as lua -v -i when stdin is a terminal.

Chunks of Lua can be also precompiled into a binary form with Luac.exe, which is also included in the win32 executables. Luac.exe is a Lua bytecode compiler, an assembler that compiles the Lua source code into bytecode. This makes it completely unreadable to normal humans but also makes it run much faster. To use the bytcode assembler, you just call it as if you were compiling and then tell it what you want the new file to be (with a .lub extension) and what the sourcefile (.lua) is.

 Luac.exe -o Myfile.lub Myfile.lua 

The -o is one option to feed Luac, which means "output to file." For a full list of Luac options, see Table 2.8.

Table 2.8. Luac Options

Option

Purpose

-l

Produce a listing of the compiled bytecode for Lua's virtual machine

-o "file"

Output to file, instead of the default luac.out

-p

Load files but do not generate any output file

-t

Perform integrity tests of precompiled chunks

-v

Print version information


NOTE

As Lua was written in ANSI C, you need to do special work when embedding Lua into a C++ application due to the "name mangling" that C++ performs . You must place extern "C" around the inclusion of Lua headers in a C++ application:

  extern "C"{   # include "lua.h"   }  

Lua has no if def cplusplus or if def c directives, because it is pure, clean ANSI C. This pureness makes the extern command necessary; without it, you will get link errors.

Lua's "Hello World"

Lua is quite different than the other two languages presented in this book. Lua is primarily an extension language, and Lua code is usually embedded within a host. You'll find Lua residing inside C, Python, and Ruby scripts, doing what it does bestacting as code within code. In-depth coverage of how to program with Lua is covered in Section 2 of this book, and what follows is just an example to whet one's appetite. With the understanding that a Lua "Hello World" program would normally exist within another language's construct, writing a "Hello World" program in Lua is even shorter and simpler than in Python or C:

 -- -- HELLO_LUA_1.lua -- This program displays the string "hello" . -- It prints the string by using an internal print command. -- print "hello world\n" 

Notice that Lua's comments are different; they are marked by two dashes (--) instead of a pound (#) sign. Also notice that the print line itself is almost exactly like the C version Hello_C_1.cpp above, except in this case that you do not need to import a library for the print command, and a few of the symbols, namely the semicolons and parentheses, are left out.

The Ruby Environment

Ruby is most used to Posix type operating systems (such as UNIX, Linux, and FreeBSD) and is written in the C programming language. Although Ruby is comfortable on UNIX, Linux, DOS, the various Windows flavors, Macintosh, and number of other platforms, it's most at home on the Posix environment where it was born.

Ruby on Windows needs a few additional tools in order to emulate its home environment. These tools include a Linux-like environment for Windows called cygwin, a collection of Windows header files and libraries called mingw, and the DJ Delorie software tools (djgpp). Precompiled versions of Ruby with these tools included can be found at the Ruby Central Website, which houses the Ruby "one-click" installer for Windows at http://www.rubycentral.com

The latest versions of this collection of tools can be found at their own respective Websites as well:

  • cygwin. http://www.cygwin.com/.

  • mingw. http://www.mingw.org/.

  • djgpp. http://www.delorie.com/.

This Windows one-click installation is also included on the CD that accompanies this book, and can be found in the Ruby folder: \RUBY

Installing Ruby

The latest version of Ruby, 1.8.0 as of this writing, can be downloaded from the Ruby language organization Website at http://www.ruby-lang.org.

Developers can also take a peek at the source tree at that location. Ruby Version 1.8.0 is also on this book's CD in the \RUBY folder.

Windows users can simply use the one-click installer executable to install Ruby on their machines; just double-click on ruby180-10.exe to run the Ruby Setup Wizard. You may have to restart your computer afterwards.

Steps for installing Ruby on a Posix environment will vary, depending on the platform and also on any extension or static module linking that needs to be done. The following condensed steps will suffice for most folks, however:

  1. Become a super user or user with privileges for installing new programs.

  2. Run autoconfto generate configure.

  3. Run ./configure to generate config.h and the makefile.

  4. Run make .

  5. Run make install .

The Ruby Interpreter

Ruby can be used interactively with the interpreter, called irb, that comes bundled with it. For UNIX machines you need to add irb/ to the $RUBYLIB environment variable and make a symbolic link to the irb.rb file in your path environment. Then you can type in irb to call the interactive Ruby shell.

On Windows, the irb is installed by default in the program file's directory, and the Ruby shell is accessible through the Start menu under Programs (see Figure 2.17). The code samples in this chapter can be run with the Interactive Ruby Shell.

Figure 2.17. Launching the Ruby interpreter from the Program menu

graphic/02fig17.gif


A program called eval, which is included in the samples/directory of the Ruby distribution, allows you to enter expressions and view their values.

Creating Ruby Program Files

Ruby program files invariably end with an .rb extension. They can be created in Notepad or vi or any other sort of text editor. To make things even easier, Ruby comes bundled with a nifty tool for scripting called the SciTE, which is a Scintilla-based text editor. SciTE has features for building and running many kinds of programs (see Figure 2.18), and it understands the syntax of a smattering of different computer languages, including Python, Lua, and Ruby.

Figure 2.18. The SciTE editor shows off its knowledge of Ruby syntax.

graphic/02fig18.gif


Executing Ruby

Ruby itself (that is, Ruby.exe) is meant to run on the command line, whether it's the UNIX shell or Windows command or DOS. The basic syntax for running Ruby is as follows:

 Ruby  options  MyProgramScript  arguments  

Being a child of the command line, Ruby accepts a number of fun command-line options, or switches; these are outlined in Table 2.9.

Ruby comes with a Ruby Windows executable called rubyw.exe that will run on a Windows environment without launching a DOS or Windows command-line window, but the Windows platform will need to have .rb files associated with the executable for launching.

Ruby is primarily used as an interpreted language or as an extension. One extremely common use is to find Ruby on a server machine like a Web server where it is used as an interpreted language to run CGI or create Web forms and cookies. Ruby can also be embedded into HTML documents, another common use of the language.

Table 2.9. Ruby Command-Line Switches

Argument

Purpose

-0digit

Specifies the input record separator ($/) as an octal number

-a

Turns on auto-split mode

-c

Checks the syntax of the script and then exits without executing

-Kc

Specifies the KANJI (Japanese character) code-set

-d

Turns on debug mode

--debug

Turns on debug mode

-e

Used to specify a script from the command line

-F

Used to specify the input field separator

-h

Prints a summary of all the command options

--help

Prints a summary of all the command options

-I

Specifies in-place-edit mode

-l

Enables automatic line-ending processing

-n

Used to run multiple iterations around the given script (looping)

-p

Same as n but prints the value of variable $_ at each end of the loop

-r

Causes Ruby to load a given file using require

-s

Enables some switch parsing for switches

-S

Forces Ruby to use the PATH environment variable to search for script

-T

Forces taint type checks to be turned on at the given level

-v

Enables verbose mode

--verbose

Enables verbose mode

--version

Prints the Ruby version

-w

Enables verbose mode without printing the version message at the beginning

-x[directory]

Tells Ruby that the script is embedded in a message and switches to a given directory (if provided) before executing a script

-X

Causes Ruby to switch to a given directory

-y

Turns on compiler debug mode

--yydebug

Turns on compiler debug mode


The most common use for games is to have Ruby associated with C as an extension. The Ruby interpreter is embeddable , and it is possible to embed the entire Ruby interpreter into C or other code. Just like Lua, Ruby has a full C API, which I'll cover in Chapter 10, and it is extendable not only with C but with other languages; I'll discuss doing that in Chapter 12.

Ruby's "Hello World"

A "Hello World" program in Ruby looks a lot like Python's:

 #!/usr/bin/ruby ############ # HELLO_RUBY_1.ruby # This program displays the string "hello" . # It first shows the path to ruby, and then prints the string. ############ puts "Hello!" 

Ruby's code is extremely streamlined in this example. A built-in puts command handles the printing without the need of any loops , spacing, brackets, or semi-colons. Very clean, this script simply tells the computer where Ruby is and then, in one line, tells it what to do.

[ LiB ]


Game Programming with Pyton, Lua and Ruby
Game Programming with Pyton, Lua and Ruby
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 133

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net