STRING


A string is a sequence of characters that is used to represent text in programming. It can be a symbol, a word, or a whole sentence. For example, you could create a string variable called "name" and assign it a value of "lua" to represent the name of the programming language.

name = "lua"

Strings can contain any combination of letters, numbers, and symbols, and can be manipulated using various string functions to perform tasks such as searching, replacing, and formatting text. The important thing is that they are surrounded by quotes (either single or double) to separate them from other types of data in your code.

abc    --not a string
"abc"  --a string
print(abc)   --fail
print("abc") --success

We can print a string directly:

print("game over")

Or we can store a string in a variable and then print the variable, which will print the string.

text = "game over"
print(text)

Combining Strings

The term we use when we talk about combining strings or variables is "concatenation" or "concat" for short. Let's say you have two strings saved as variables, "player_name" and "level_name":

player_name = "samantha"
level_name = "haunted mansion"

And you want to display a message that greets the player by name and tells them which level they are playing. Here's how you can concatenate the string variables into one long string using double dots (..) like this:

message = player_name.." is playing "..level_Name

print(message)

Prints: "samantha is playing haunted mansion"

You can also concatenate strings with number variables like this:

highscore = 123
message = player_name.." = "..highscore

print(message)

Prints: "samantha = 123"


Overall, strings are an important data type that you will want to use for any text you want to display on the screen.

Images in this Guide by NerdyTeachers is licensed under CC BY-SA 4.0

609

9 Mar 2023

Font