So in many scripts, there are parenthesis, brackets, and braces. I know what the function of parenthesis and braces are, but what is the point of brackets []? And when do you use them? I would really appreciate if someone would answer!
(Round) Parenthesis ()
have two purposes in Lua:
(1 + 2) * 4
is 3 * 4
rather than 1 + 8
.print( 5 )
, a name followed by (
indicates that you call (use) that name as a function. They are read like of. For example, math.sqrt( 5 )
is "the square root of 5".Square brackets/braces []
are used in a way similar to ()
when calling -- they are used to index. They answer what is at a location.
list[1]
is the thing at position 1 in list
.
map[blah]
is the thing at the key with the value blah
inside map
, map["prop"]
gets the property called prop in map
.
Curly braces {}
are used to define tables -- tables have two main forms -- dictionaries (also called maps or hashmaps) and lists (also called arrays).
The things inside of a table are separated by commas ,
or semicolons ;
(these are equivalent). Usually ,
is used. Note that you are allowed to have a "trailing" comma or semicolon. This is ungrammatical in English but can be desirable for programming (especially with version control)
Entries in a table have three forms:
List values are simply the bare value: list = {1, 2, 3}
.
Named properties can be written with a property=value
format:
Bob = { name = "Bob", occupation = "Programmer", age = 20, }
Properties at others keys can be used using []
to indicate where they are in the form [key] = value
:
Bob = { ["name"] = "Bob", ["favorite-color"] = "blue", [1995] = "birth", [math] = "favorite library", }
Square brackets are for Arrays and Tables. For example, in this table:
local Table = {"First", "Second", "Third"}
To access "Second" you would say:
Table[2]