Преобразование массива

Массивы и коллекции / Массивы

local numbers = {1, 2, 3, 4, 5}

-- Every item goes through the conversion
local tripled = {}
for index, number in ipairs(numbers) do
  tripled[index] = number * 3
end
-- tripled = 3, 6, 9, 12, 15

-- The same loop as a function:
-- the conversion comes as an argument
local function map(list, convert)
  local result = {}
  for index, item in ipairs(list) do
    result[index] = convert(item)
  end
  return result
end

-- A ready-made function works as it is
local labels = map(tripled, tostring)
-- labels = 3, 6, 9, 12, 15
local label_type = type(labels[1])
-- label_type = string

print("tripled = " .. table.concat(tripled, ", "))
print("labels = " .. table.concat(labels, ", "))
print("label_type = " .. label_type)