We're starting to familiarize ourselves with several blocks of code and how they interact with each other. Let's see what happens when we add in some expressions using strings and how different they are from just regular strings that you print out in the terminal:
Working With Strings
.main.lua
file in your text editor and save it to your folder.1 print("This is a string!") -- This is a string! 2 print("15" + 1) -- Returns the value 16
3 myVar = 28 4 print(myVar) -- Returns 28 5 myVar = "twenty-eight" 6 print(myVar) -- Returns twenty-eight
7 Name1, Phone = "John Doe", "123-456-7890" 8 Name2 = "John Doe" 9 print(Name1, Phone) -- John Doe 123-456-7890 10 print(Name1 == Phone) -- false 11 print(Name1 <= Phone) -- false 12 print(Name1 == Name2) -- true
This is a string! 16 28 twenty-eight John Doe 123-456-7890 false false true
You can see that line 1 is just a plain string with characters printed out. In line 2, notice that number 15
is inside the string and then added to the number 1
, which is outside of the string. Lua provides automatic conversions between numbers and strings at runtime. Numeric operations applied to a string will try to convert the string to a number.
When working with variables, you can use the same one and have them contain a string and a number at different times, like in lines 3 and 5 (myVar = 28
and myVar = "twenty-eight"
).
In the last chunk of code (lines 7-12), we compared different variable names using relational operators. First, we printed the strings of Name1
and Phone
. The next lines that follow compared Name1
, Name2
, and Phone
. When two strings have the same characters in the exact order, then they are considered the same string and are equal to each other. When you look at print(Name1 == Phone)
and print(Name1 <= Phone)
, the statement returns false
because of the ASCII order. Digits are before alphabets, which are smaller when you compare them. In print(Name1 == Name2)
, both variables contain the same characters, and therefore, it returns true
.
Strings are pretty simple to work with since they are just sequences of characters. Try making your own expressions similar to the preceding example with the following modifications: