Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are curly brackets used in Lua?

Tags:

syntax

lua

If curly brackets ('{' and '}') are used in Lua, what are they used for?

like image 773
Sydius Avatar asked Mar 26 '09 18:03

Sydius


2 Answers

Table literals.

The table is the central type in Lua, and can be treated as either an associative array (hash table or dictionary) or as an ordinary array. The keys can be values of any Lua type except nil, and the elements of a table can hold any value except nil.

Array member access is made more efficient than hash key access behind the scenes, but the details don't usually matter. That actually makes handling sparse arrays handy since storage only need be allocated for those cells that contain a value at all.

This does lead to a universal 1-based array idiom that feels a little strange to a C programmer.

For example

a = { 1, 2, 3 }

creates an array stored in the variable a with three elements that (coincidentally) have the same values as their indices. Because the elements are stored at sequential indices beginning with 1, the length of a (given by #a or table.getn(a)) is 3.

Initializing a table with non-integer keys can be done like this:

b = { one=1, pi=3.14, ["half pi"]=1.57, [function() return 17 end]=42 }

where b will have entries named "one", "pi", "half pi", and an anonymous function. Of course, looking up that last element without iterating the table might be tricky unless a copy of that very function is stored in some other variable.

Another place that curly braces appear is really the same semantic meaning, but it is concealed (for a new user of Lua) behind some syntactic sugar. It is common to write functions that take a single argument that should be a table. In that case, calling the function does not require use of parenthesis. This results in code that seems to contain a mix of () and {} both apparently used as a function call operator.

btn = iup.button{title="ok"}

is equivalent to

btn = iup.button({title="ok"})

but is also less hard on the eyes. Incidentally, calling a single-argument function with a literal value also works for string literals.

like image 176
RBerteig Avatar answered Sep 22 '22 03:09

RBerteig


list/ditionary constructor (i.e. table type constructor).

They are not used for code blocks if that's what you mean. For that Lua just uses the end keyword to end the block.

See here

like image 20
Brian R. Bondy Avatar answered Sep 22 '22 03:09

Brian R. Bondy