String Buffers


As with most programming languages, Lua strings are immutable, meaning that they cannot be modified after they are created. Changing a string requires creating a new string that consists of the characters of the previous string, plus whatever changes are made to it. While simple concatenation is fine for small changes, creating a new string for every change becomes very inefficient for larger changes and should be avoided when possible.

One way to overcome this inefficiency is the string buffer, which offers a more efficient means of "composing" strings from many smaller strings. String buffers are implemented in Lua using tables, and more specifically they are an application of lists. This means that all of the topics discussed in the lists section apply to string buffers, and this section will focus only on the string buffer application.

Let's jump right into an example, starting with the following list of strings. Implementing a string buffer involves creating a list, populating it with each component string, then finally compiling the final string using the table.concat function.

Let's demonstrate using the following list:

local x = {
    "this",
    "is",
    "a",
    "string",
}

then concatenate the list into the final string:

print(table.concat(x, " ")) -- this is a string

Note that each sub-string is separated by a space, which was passed to the table.concat function. We could have passed another separator, such as a -:

print(table.concat(x, "-")) -- this-is-a-string

That's about all it takes. Of course, compiling the list will generally be more complicated than this example, and will involve one of more of the methods discussed in the list section, but once the list is populated this is all it takes.