Chapter 5. Using Strings
The last chapter covered tables and the table library. You already know strings, but you don't know the string library, and that's the main topic of this chapter. Among many other things, you'll learn about the following:
Converting between uppercase and lowercase
Getting individual characters and substrings out of strings
Getting user input
Reading from and writing to files
Doing pattern matching and replacement on strings (which is very powerful, and accounts for more than half of the chapter)
Basic String Conversion Functions
Many of the functions in the string library take a single string argument (and, in a few cases, one or two numeric arguments) and return a single string. In the following example, string.lower
takes a string and returns a string that's the same except that any uppercase letters have been converted to lowercase:
> print(string.lower("HELLO there!"))
hello there!
Of course, string.lower
doesn't care if the string given to it contains no uppercase letters, or no letters at all — just returns the same string as shown here:
>print(string.lower("hello there!"))
hello there! >print(string.lower("1 2 3 4"))
1 2 3 4
You may occasionally find yourself doing something like the following, and wondering why Str
hasn't been changed to "abc"
:
>Str = "ABC"
>string.lower(Str)
>print(Str)
ABC
If you think about it, you'll see that this is because strings are immutable, so it's impossible for a function like string.lower
to work by side effect the way functions ...
Get Beginning Lua Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.