page 5  (15 pages)
to previous section4
6to next section

can be directly implemented by tables. Tables can also simulate records by simply using field names as indices. Lua supports this representation by providing a.name as syntactic sugar for a["name"].

Unlike other languages that implement associative arrays, such as AWK [10], Tcl [11], and Perl [12], tables in Lua are not bound to a variable name; instead, they are dynamically created objects that can be manipulated much like pointers in conventional languages. The disadvantage of this choice is that a table must be explicitly created before used. The advantage is that tables can freely refer to other tables, and therefore have expressive power to model recursive data types, and to create generic graph structures, possibly with cycles. As an example, Figure 4 shows how to build linked lists in Lua.

list = {} -- creates an empty table
current = list

i = while i < 10 do
current.value = i
current.next = {}
current = current.next
i = i+1
end
current.value = i
current.next = list

Figure 4: A circular linked list in Lua

Lua provides a number of interesting ways for creating a table. The simplest form is the expression {}, which returns a new empty table. A more descriptive way, which creates a table and initializes some fields, is shown below; the syntax is somewhat inspired in the BibTEX database format [13]:

window1 = {x = 200, y = 300, foreground = "blue"}

This command creates a table, initializes its fields x, y, and foreground, and assigns it to the variable window1. Note that tables need not be homogeneous; they can simultaneously store values of all types. A similar syntax can be used to create lists:

colors = {"blue", "yellow", "red", "green", "black"}

This statement is equivalent to:

colors = {}
colors[1] = "blue"; colors[2] = "yellow"; colors[3] = "red"
colors[4] = "green"; colors[5] = "black"

Sometimes, more powerful constructor facilities are needed. Instead of trying to provide everything, Lua provides a simple constructor mechanism. Constructors are written name{...}, which is just syntactic sugar for name({...}); that is, a table is created, initialized, and passed as parameter to a function. This function can do whatever initialization is needed, such as (dynamic) type checking, initialization of absent fields, and auxiliary data structures update (even in the host program). Typically, the constructor function is pre-defined, in C or in Lua, but often configuration users are not aware that the constructor is a function; they simply write something like:

window1 = Window{ x = 200, y = 300, foreground = "blue" }

and think about windows" and other high level abstractions. Thus, although Lua is dynamically typed, it provides user controlled type constructors.