3
TALKING TO YOUR TURTLE

image

IT’S ALIVE! In Chapter 2, you created your first turtle robot, fueled it, and brought it to life. Your robotic creation has a body, but it doesn’t have much in the way of a brain. A Minecraft turtle’s brain is its program, which tells it what to do. Without a program to run, your robot doesn’t do anything. Let’s give the robot a bit of personality by writing a program that lets us talk with it.

TEACHING YOUR TURTLE TO SAY HELLO!

We’ll use the turtle’s edit program to create a new file and write and edit our first program. Programs like the edit program, which we use to write other programs, are called text editors. Right-click the turtle to open its GUI, and then enter the following into the command shell:

> edit hello

Whenever you want to create or open a file, you’ll write the keyword edit followed by the filename. The edit hello code runs the edit program and creates and opens a hello file to edit. In the file, we’ll write the instructions for our program. The instructions will all run one after another instead of one at a time like when we were entering them into the Lua shell in Chapter 2. The hello program will display Hello, world! on the screen—a traditional program for new programmers to write.

Even though the text editor doesn’t have a lot of room, you’ll still be able to type long instructions on one line. To move the blinking cursor to other lines, use the keyboard keys listed in Table 3-1.

Table 3-1: Keyboard Keys to Move the Text Editor’s Cursor

Keyboard keys

Cursor action

Up, Down, Left, Right

Moves the cursor in the key’s direction

PgUp, PgDn

Moves the cursor several lines up or down at a time

Backspace

Erases the text behind the cursor

Delete

Erases the text in front of the cursor

Home

Moves the cursor to the start of the line

End

Moves the cursor to the end of the line

Tab

Can autocomplete an instruction you’ve started to type

A program’s instructions are called its source code. Enter the following source code for the hello program into the editor, but don’t type the number, period, and space at the beginning of each line. The line numbers are just used for reference in this book. I’ll explain the code step by step in this chapter, so don’t worry about what each line means for now.

hello

1. print('Hello, world!')
2. print('I am ' .. os.getComputerLabel())
3. print('What is your name?')
4. name = io.read()
5. textutils.slowPrint('Nice to meet you, ' .. name)

When you finish entering the code, press the CTRL key to bring up the Save/Exit menu at the bottom of the shell. The edit program will look like Figure 3-1 when the menu is open.

image

Figure 3-1: The hello program typed into the editor

The [Save] option has brackets around it to highlight it. Press ENTER to save the hello file on the turtle so you can access, edit, and run the program later. Then press CTRL to bring up the Save/Exit menu again. Press the right arrow key to highlight [Exit], and press ENTER to take you out of the file and back to the command shell prompt.

RUNNING THE HELLO PROGRAM

In the command shell, you can run the hello program the same way you ran the label, dance, and refuel programs. Just enter hello in the command shell:

> hello
Hello, world!
I am Sofonisba
What is your name?

The turtle says hello, introduces itself, and waits for you to type your name. After I enter my name, Al, the program looks like this:

> hello
Hello, world!
I am Sofonisba
What is your name?
Al
Nice to meet you, Al

When the program finishes, it returns to the > prompt and is ready for you to run another program.

The software that runs programs written in the Lua programming language is called the Lua interpreter. We shorten the name of the interpreter and call it Lua, so Lua refers to both the programming language and the software that runs code written in that language. The place in the code where the Lua interpreter is currently running instructions is called the execution. The execution always starts at the first line of a program. It executes (or runs) the instruction on line 1. Then it moves down and executes each instruction, or line of source code.

Look at the text the program produced, and then look back at the hello program’s source code. Before moving on to the explanation, try to figure out on your own what each line of code does. Try modifying the print('Hello, world!') line to print('Greetings') instead. Then save the program, exit the editor, and run the hello program again to see what changed. These are the steps you use to become a skilled programmer: guess what the code does, determine whether your guess is correct, figure out why your guess is incorrect (if it is), and experiment with the code to see what changes.

LISTING ALL FILES WITH THE LS COMMAND

If you forget which files you have on a turtle, you can run the ls (or “list,” note the lowercase “l”) command to list them. Enter the following into the command shell:

> ls
rom
hello

The ls command lists files, including programs, and folders that contain other files. The rom folder contains other files that come with the turtle, but we won’t be using them in this book.

DISPLAYING TEXT WITH THE PRINT() FUNCTION

Let’s look at the hello program line by line. The first line is as follows:

hello

1. print('Hello, world!')

This line is a function call to the print() function, which makes the Hello, world! text appear. You can experiment with the print() function at the Lua shell. Run the lua program, and enter the following.

lua> print('Hello, world!')
Hello, world!
1

When you want to determine how a piece of code works, you can enter it into the Lua shell to examine what it does. As you can see, the print() function displays text on the screen. The 1 at the end is the return value of the print() function, which is the number of lines of text that were printed. The 1 won’t appear when you call the print() function in a program like hello. It only appears here because the Lua shell helpfully displays the return values of all functions.

Recall from Chapter 2 that the math.random() function took two values inside the parentheses when it was called. These arguments told the function the range for the random number it should return. The print() function also takes an argument, which in this case is 'Hello, world!'. This kind of text value is known as a string, which you’ll learn about next.

THE STRING DATA TYPE

You’ve used number values, such as 2 and 10, in your programs, but you’ll also want to use letters. Strings are a type of value that contain text instead of numbers. Similar to number values, strings can be stored in variables or used in expressions. Strings and numbers are the data types of these values. You’ll learn about other data types, such as Booleans and nil, in Chapter 5.

Because strings are made up of letters that could look like Lua commands, Lua needs to know when a string value begins and ends so it doesn’t confuse it as Lua code. Strings begin and end with a single quote ('), as in 'Hello, world!'. The single quote is not a part of the text; it just marks where the text begins and ends in your source code. You can also use double quotes ("), as in "Hello, world!".

You can also use a string value with no text at all between the two quotes: ''. This is called an empty string.

STRINGING STRINGS TOGETHER WITH CONCATENATION

Let’s look at line 2 in the hello program’s source code:

hello

2. print('I am ' .. os.getComputerLabel())

Line 2 has a call to the print() function, but the value we pass to print() has some new Lua code. The .. is called the string concatenation operator. It behaves like the + operator for numbers except it’s for strings. Just like the + operator can combine two numbers together into a new number, the .. operator can concatenate, or combine, two string values into a single string. Enter the following into the Lua shell:

lua> 'Hello,' .. 'world!'
Hello,world!

This line of code is an expression, just like 2 + 2. 'Hello,' and 'world!' are values, and .. is an operator. Like all expressions, 'Hello,' .. 'world!' evaluates to a single value, which in this case is the string 'Hello,world!'.

Lua doesn’t add spaces when you concatenate strings. Because neither of the two strings in our example had a space, there is no space between the words in the evaluated string. If you want a space between your text, you must add it to one of the two strings’ values. For example, 'Hello, ' .. 'world!' or 'Hello,' .. ' world!' will evaluate to 'Hello, world!'.

Line 2 of the program concatenates the two strings 'I am ' and the string returned by a new function named os.getComputerLabel(). We’ll look at how this function works in the next section.

RETRIEVING TURTLE NAMES

In Chapter 2, you set the turtle’s name using the label program. Your programs can retrieve this name as a string value using the os.getComputerLabel() function. Function calls can be part of an expression, just like values, because a function call evaluates to its return value. Enter the following into the Lua shell to see how this function works:

lua> os.getComputerLabel()
Sofonisba
lua> turtleName = os.getComputerLabel()
lua> print(turtleName)
Sofonisba
1

The function call evaluates to a string value of the turtle’s name, so turtleName = os.getComputerLabel() is the same as turtleName = 'Sofonisba'.

Take another look at line 2 in the hello program:

hello

2. print('I am ' .. os.getComputerLabel())

The expression 'I am ' .. os.getComputerLabel() concatenates the turtle’s name with the string 'I am ' to evaluate to a single string. This single string is passed to the print() function, which is why I am Sofonisba appears on the screen when the program is run. Line 2 is just an expression that evaluates to a single value, as shown here:

image

Remember that the print() function returns a value of the number of lines it printed, which is why it evaluates to 1. The string value that the print() function prints isn’t its return value.

GETTING KEYBOARD INPUT WITH THE IO.READ() FUNCTION

Look at lines 3 and 4 in the hello program:

hello

3. print('What is your name?')
4. name = io.read()

Line 3 is another call to print(). But line 4 has a new function: io.read(). When called, the io.read() function pauses the program until the player types something and presses ENTER. The text the player inputs is returned from io.read() as a string, which is assigned to the variable name.

If the player entered Al, name would be assigned the string value 'Al'.

BONUS ACTIVITY: PROPER INTRODUCTIONS

You’ve written a hello program to tell the turtle your name, but you can also tell the turtle a bit more about yourself. Write a program where the turtle asks the player for not only their name but also their age and favorite video game. Save each of these responses in separate variables, and then use the print() function and .. operator to display them back to the player.

GIVING TEXT A TYPEWRITER EFFECT

You may have noticed when you ran the hello program that the text in the last line was displayed letter by letter as though it was slowly being typed with a typewriter. This is done using the textutils.slowPrint() function:

hello

5. textutils.slowPrint('Nice to meet you, ' .. name)

The argument to slowPrint() is the string 'Nice to meet you, ' concatenated with the string in the variable name, which is how the program says hello to the player using their name. Line 5 is the last line of code, so the program terminates, or quits, after it’s executed.

CHANGING TURTLE NAMES

You can change the turtle’s name by calling the os.setComputerLabel() function and passing it a string value. Enter the following code into the Lua shell.

lua> os.setComputerLabel('Elisabetta')
lua> os.getComputerLabel()
Elisabetta

Your turtle’s name is now Elisabetta. You can rename your turtle as many times as you’d like using the os.setComputerLabel() function.

BONUS ACTIVITY: A TURTLE BY ANY OTHER NAME

Try writing your own version of the label program. You can run edit mylabel to create the file. Have your program call print() and io.read() to ask the player for the turtle’s new name, and then pass that name to the os.setComputerLabel() function.

WHAT YOU LEARNED

In this chapter, we created a “Hello, world!” program, which is a customary first program for new programmers to make. This program can output text (using the print() and textutils.slowPrint() functions) and input text (using the io.read() function). In Lua, text takes the form of string values, which can be stored in variables or used in expressions, just like number values.

String values also have operators, just like number values. The .. string concatenation operator can combine multiple strings to form one new string.

The hello program in this chapter was just the first step in writing programs for your robots. In Chapter 4, you’ll learn a few more concepts and functions to make the turtle move (and dance!) around.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.122.4