Linux Format

About tables in Lua

-

The bad news is that tables are the only ‘container’ type in Lua. The good thing is that Lua tables are very flexible and powerful as they are associativ­e arrays, which means that they can store any kind of key and value pairs. The following Lua code shows how to create and use a table: > aTable = {} -- define an empty table > print(aTable) table: 0x7f872350­02b0 > aTable[0] = “zero” > aTable[1] = “one” > =aTable[0] zero

> return aTable[2] nil

It’s required that you first declare an empty array before adding elements to it. As you can see from the last line of the previous output, if there is not a value associated to a key, the return value will be “nil” – assigning “nil” to an existing key erases the key and value pair from the table. The aforementi­oned example shows how to use a Lua table as a traditiona­l array but you can also define elements as:

aTable["key"] = “value” As you can understand, a Lua array can contain multiple types of keys at the same time.

You can easily generate a table without the need to manually add index numbers using the following way:

> anotherTab­le = {"one”, “two”, “three”, “four"}

Note that the index of the first element is 1. If you are going to use constant strings as keys, you can use a special shortcut syntax offered by Lua: > aTable.stringCons­tant = “anotherVal­ue" .

The following code shows how to print all elements of an associativ­e array which is pretty much what other programmin­g languages do: > for key,value in pairs(aTable) do print(key,value) end

Newspapers in English

Newspapers from Australia