In this project, we will create a finite loop the validates user input from the terminal.
So far, we have learned how to display or "print" text to the terminal. If you are familiar with the terminal, you would know we can also do the opposite. GLang makes this very easy for you with the chew built in.
chew("Enter some text: ");
Upon running this program, the terminal will halt with the message Enter some text:. Essentially, GLang is waiting for user input before continuing through the program.
Let's write our newly found while loop to run an infinite loop retrieving user input:
while true {
chew("Enter some text: ");
}
This will create an infinite loop retrieving text from the terminal.
However, one thing about the chew function, is that it returns a string of the entered text. We can get this string by creating a new object to represent it:
while true {
obj usr_input = chew("Enter some text: ");
bark("You entered: " + usr_input);
}
Let's take it a step further, and validate what the user typed with an if statement:
while true {
obj usr_input = chew("Enter a command: ");
if usr_input == "exit" {
leave; # break the loop to exit
} alsoif usr_input == "speak" {
bark("Hello, I am Bob the computer!");
} otherwise {
bark("You entered: " + usr_input);
}
}
if statements are ways to conditionally check what something equals, isn't equaling, is greater than, is less than, is true, or is false. We'll touch on if statements in Chapter 9.