O'Reilly logo

Beginning Lua Programming by Kurt Jung, Aaron Brown

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required