In this project, we will create a loop that builds a list of values based on user input and prints them out to the terminal.
To start, we need to create a loop that gets user input, and initializes our newly found list type:
obj inputs = [];
while true {
obj text = chew("Enter some text: ");
}
Let's add the typed text to our list object:
obj inputs = [];
while true {
obj text = chew("Enter some text: ");
obj inputs = push(inputs, text);
}
For now, this just creates an infinite loop slowly building a list based on user input. It might be helpful to check the length of the list and stop the loop eventually:
obj inputs = [];
while true {
if length(inputs) == 5 {
leave;
}
obj text = chew("Enter some text: ");
obj inputs = push(inputs, text);
}
This will stop the program once we hit 5 items pushed to the list. You can check the size of a list or string with length.
Now what about the display part? We need a way to iterate through the list. The most common way is to use the walk loop like so:
walk i = 0 through length(inputs) {
bark(i);
}
This will print each index the size of length(inputs). We can then retrieve that index to get the value at that point in the list:
walk i = 0 through length(inputs) {
bark(retrieve(inputs, i));
}
Now that we can iterate through the list, we can use the std_format module to format our text with the value in the list:
fetch std_format; # imports the std_format module, we'll touch on this later
# ...
walk i = 0 through length(inputs) {
bark(format("You typed 5 items, one of them was: {}", retrieve(inputs, i)));
}
And boom! Run your program, type 5 individual things, and see the output!
The final end program should look something like:
fetch std_format;
obj inputs = [];
while true {
if length(inputs) == 5 {
leave;
}
obj text = chew("Enter some text: ");
obj inputs = push(inputs, text);
}
walk i = 0 through length(inputs) {
bark(format("You typed 5 items, one of them was: {}", retrieve(inputs, i)));
}