Comprehensions
Comprehensions provide a convenient syntax for constructing a new table by iterating over some existing object and applying an expression to its values. There are two kinds of comprehensions: list comprehensions and table comprehensions. They both produce Lua tables; list comprehensions accumulate values into an array-like table, and table comprehensions let you set both the key and the value on each iteration. List Comprehensions
The following creates a copy of the items table but with all the values doubled.
MoonScript:
items = { 1, 2, 3, 4 }
doubled = [item * 2 for i, item in ipairs items]
Lua:
local items = {
1,
2,
3,
4
}
local doubled
do
local _accum_0 = { }
local _len_0 = 1
for i, item in ipairs(items) do
_accum_0[_len_0] = item * 2
_len_0 = _len_0 + 1
end
doubled = _accum_0
end
The items included in the new table can be restricted with a when clause:
MoonScript:
iter = ipairs items
slice = [item for i, item in iter when i > 1 and i < 3]
Lua:
local iter = ipairs(items)
local slice
do
local _accum_0 = { }
local _len_0 = 1
for i, item in iter do
if i > 1 and i < 3 then
_accum_0[_len_0] = item
_len_0 = _len_0 + 1
end
end
slice = _accum_0
end
Because it is common to iterate over the values of a numerically indexed table, an * operator is introduced. The doubled example can be rewritten as:
doubled = [item * 2 for item in *items]
Lua:
local doubled
do
local _accum_0 = { }
local _len_0 = 1
local _list_0 = items
for _index_0 = 1, #_list_0 do
local item = _list_0[_index_0]
_accum_0[_len_0] = item * 2
_len_0 = _len_0 + 1
end
doubled = _accum_0
end
The for and when clauses can be chained as much as desired. The only requirement is that a comprehension has at least one for clause.
Using multiple for clauses is the same as using nested loops:
MoonScript:
x_coords = {4, 5, 6, 7}
y_coords = {9, 2, 3}
points = [{x,y} for x in *x_coords for y in *y_coords]
Lua:
local x_coords = {
4,
5,
6,
7
}
local y_coords = {
9,
2,
3
}
local points
do
local _accum_0 = { }
local _len_0 = 1
for _index_0 = 1, #x_coords do
local x = x_coords[_index_0]
for _index_1 = 1, #y_coords do
local y = y_coords[_index_1]
_accum_0[_len_0] = {
x,
y
}
_len_0 = _len_0 + 1
end
end
points = _accum_0
end
Numeric for loops can also be used in comprehensions:
MoonScript:
evens = [i for i=1,100 when i % 2 == 0]
Lua:
local evens
do
local _accum_0 = { }
local _len_0 = 1
for i = 1, 100 do
if i % 2 == 0 then
_accum_0[_len_0] = i
_len_0 = _len_0 + 1
end
end
evens = _accum_0
end