Slicing

A special syntax is provided to restrict the items that are iterated over when using the * operator. This is equivalent to setting the iteration bounds and a step size in a for loop.

Here we can set the minimum and maximum bounds, taking all items with indexes between 1 and 5 inclusive:

MoonScript:

slice = [item for item in *items[1,5]]

Lua:

local slice
do
  local _accum_0 = { }
  local _len_0 = 1
  local _list_0 = items
  local _max_0 = 5
  for _index_0 = 1, _max_0 < 0 and #_list_0 + _max_0 or _max_0 do
    local item = _list_0[_index_0]
    _accum_0[_len_0] = item
    _len_0 = _len_0 + 1
  end
  slice = _accum_0
end

Any of the slice arguments can be left off to use a sensible default. In this example, if the max index is left off it defaults to the length of the table. This will take everything but the first element:

MoonScript:

slice = [item for item in *items[2,]]

Lua:

local slice
do
  local _accum_0 = { }
  local _len_0 = 1
  local _list_0 = items
  for _index_0 = 2, #_list_0 do
    local item = _list_0[_index_0]
    _accum_0[_len_0] = item
    _len_0 = _len_0 + 1
  end
  slice = _accum_0
end

If the minimum bound is left out, it defaults to 1. Here we only provide a step size and leave the other bounds blank. This takes all odd indexed items: (1, 3, 5, …)

slice = [item for item in *items[,,2]]

Lua:

local slice
do
  local _accum_0 = { }
  local _len_0 = 1
  local _list_0 = items
  for _index_0 = 1, #_list_0, 2 do
    local item = _list_0[_index_0]
    _accum_0[_len_0] = item
    _len_0 = _len_0 + 1
  end
  slice = _accum_0
end

results matching ""

    No results matching ""