Table Comprehensions
The syntax for table comprehensions is very similar, only differing by using { and } and taking two values from each iteration.
This example makes a copy of the tablething:
thing = {
color: "red"
name: "fast"
width: 123
}
thing_copy = {k,v for k,v in pairs thing}
Lua:
local thing = {
color = "red",
name = "fast",
width = 123
}
local thing_copy
do
local _tbl_0 = { }
for k, v in pairs(thing) do
_tbl_0[k] = v
end
thing_copy = _tbl_0
end
Table comprehensions, like list comprehensions, also support multiple for and when clauses. In this example we use a when clause to prevent the value associated with the color key from being copied.
MoonScript:
no_color = {k,v for k,v in pairs thing when k != "color"}
Lua:
local no_color
do
local _tbl_0 = { }
for k, v in pairs(thing) do
if k ~= "color" then
_tbl_0[k] = v
end
end
no_color = _tbl_0
end
The * operator is also supported. Here we create a square root look up table for a few numbers.
numbers = {1,2,3,4}
sqrts = {i, math.sqrt i for i in *numbers}
Lua:
local numbers = {
1,
2,
3,
4
}
local sqrts
do
local _tbl_0 = { }
for _index_0 = 1, #numbers do
local i = numbers[_index_0]
_tbl_0[i] = math.sqrt(i)
end
sqrts = _tbl_0
end
The key-value tuple in a table comprehension can also come from a single expression, in which case the expression should return two values. The first is used as the key and the second is used as the value:
In this example we convert an array of pairs to a table where the first item in the pair is the key and the second is the value.
tuples = {{"hello", "world"}, {"foo", "bar"}}
tbl = {unpack tuple for tuple in *tuples}
Lua:
local tuples = {
{
"hello",
"world"
},
{
"foo",
"bar"
}
}
local tbl
do
local _tbl_0 = { }
for _index_0 = 1, #tuples do
local tuple = tuples[_index_0]
local _key_0, _val_0 = unpack(tuple)
_tbl_0[_key_0] = _val_0
end
tbl = _tbl_0
end