Learning Lua

Below is my humble attempt to duplicate Randal Schwartz's excellent language introduction from the book Learning Perl, published by O'Reilly. My examples follow the same functionality Randal's did (except that they are in Lua), but the explanation text is my own.

Hello World!

Since all language tutorials start with a "Hello World" program, this one will too.

#!/usr/bin/lua
print ("Hello World!")

Any person familiar with Unix shell scripting should recognize the first line. It simply tells the shell to call the /usr/bin/lua program to execute the following lines. Note that is isn't actually a part of a Lua program, but only necessary if you plan to run the program as a shell script.

The second line displays the text "Hello World!" on the screen. If you are familiar with other programming languages, you may notice that the newline character (\n) is missing. Lua's print command automatically adds the newline for you, much like Java's println function.

If you're a C programmer, you might be disturbed that the print statement is not ended in a semicolon. Don't be too disturbed, because semicolons (and parenthesis for that matter) are completely optional in Lua.

Getting User Input

Printing lines of text is great, but most of the time our programs need to be a little more useful. One common task of many programs is reading input from the user, so let's expand our program to do just that.

#!/usr/bin/lua
write ("What is your name? ")
name = read ()
print ("Hello " .. name)

The first line uses the write statement, which we haven't seen before. write has exactly the same functionality as print, but does not automatically print a newline at the end of the statement.

The second line reads a string from the terminal and places it in the variable name. It may be important to note that when reading a string, the newline character is stripped from the end before being sent to the variable.

Variables in Lua are dynamically typed, which means that the variables themselves do not have a type, but the values they hold have a type. In this case, the value stored in name by read is a string. Values can have one of six types in Lua: nil, number, string, function, userdata, and table

The third line prints out a message to the person whose name was just entered. The .. operator is the string concatenation operator in Lua. Since name contains a string, the result is that the entered name is printed after "Hello " on the screen.

Making Choices

Our little program does its job well, but what if we want to add a customized greeting for a certain individual? Let's add a little bit more to the program to add a special message for someone named "Randal".

#!/usr/bin/lua
write ("What is your name? ")
name = read("*l")

if name == "Randal" then
	print ("Hello, Randal! How good of you to be here!")
else
	print ("Hello " .. name .. "!") -- ordinary greeting
end

No real surprises here, but this example shows nicely how conditional statements work in Lua. if statements are simple. If the condition (between if and then) is true, then every line between then and the next else, elseif, or end statement is executed. Between an if/end pair, any number of elseif/then statements can be inserted, and up to one else statement. The else statement is executed only if none of the previous specified conditions are true. When end is reached, normal program execution resumes.

This listing also demonstrates another important feature of Lua: comments. In Lua, everything after "--" on a single line is considered a comment and is not processed by the interpreter. Most programmers insert comments around code that is difficult to understand or they may need to come back to later.

Guess the Secret Word

Now our program can recognize a specific user. The program is not very useful in a real world situation yet, but let's change that. Let's suppose we wanted to use the program as a sort of login manager. We want people named "Randal" to have access, but anyone else that wants to get in has to guess a secret word.

#!/usr/bin/lua
secretword = "llama" -- the secret word

write ("What is your name? ")
name = read ("*l")

if name == "Randal" then
	print ("Hello, Randal! How good of you to be here!")
else
	print ("Hello " .. name .. "!") -- ordinary greeting
	write ("What is the secret word? ")
	guess = read ("*l")
	while guess ~= secretword do
		write ("Wrong, try again. What is the secret word? ")
		guess = read ("*l")
	end
end