Table Literals
Like in Lua, tables are delimited in curly braces.
MoonScript:
some_values = { 1, 2, 3, 4 }
Lua:
local some_values = {
1,
2,
3,
4
}
Unlike Lua, assigning a value to a key in a table is done with : (instead of =).
MoonScript:
some_values = {
name: "Bill",
age: 200,
["favorite food"]: "rice"
}
Lua:
local some_values = {
name = "Bill",
age = 200,
["favorite food"] = "rice"
}
The curly braces can be left off if a single table of key value pairs is being assigned.
MoonScript:
profile =
height: "4 feet",
shoe_size: 13,
favorite_foods: {"ice cream", "donuts"}
Lua:
local profile = {
height = "4 feet",
shoe_size = 13,
favorite_foods = {
"ice cream",
"donuts"
}
}
Newlines can be used to delimit values instead of a comma (or both):
MoonScript:
values = {
1,2,3,4
5,6,7,8
name: "superman"
occupation: "crime fighting"
}
Lua:
local values = {
1,
2,
3,
4,
5,
6,
7,
8,
name = "superman",
occupation = "crime fighting"
}
When creating a single line table literal, the curly braces can also be left off:
MoonScript:
my_function dance: "Tango", partner: "none"
y = type: "dog", legs: 4, tails: 1
Lua:
my_function({
dance = "Tango",
partner = "none"
})
local y = {
type = "dog",
legs = 4,
tails = 1
}
The keys of a table literal can be language keywords without being escaped:
MoonScript:
tbl = {
do: "something"
end: "hunger"
}
Lua:
local tbl = {
["do"] = "something",
["end"] = "hunger"
}
If you are constructing a table out of variables and wish the keys to be the same as the variable names, then the : prefix operator can be used:
MoonScript:
hair = "golden"
height = 200
person = { :hair, :height, shoe_size: 40 }
print_table :hair, :height
Lua:
local hair = "golden"
local height = 200
local person = {
hair = hair,
height = height,
shoe_size = 40
}
print_table({
hair = hair,
height = height
})
If you want the key of a field in the table to to be result of an expression, then you can wrap it in [ ], just like in Lua. You can also use a string literal directly as a key, leaving out the square brackets. This is useful if your key has any special characters.
MoonScript:
t = {
[1 + 2]: "hello"
"hello world": true
}
Lua:
local t = {
[1 + 2] = "hello",
["hello world"] = true
}