local numbers = {1, 2, 3, 4, 5}
-- 每个元素都经过转换
local tripled = {}
for index, number in ipairs(numbers) do
tripled[index] = number * 3
end
-- tripled = 3, 6, 9, 12, 15
-- 把同样的循环写成函数:
-- 转换作为参数传入
local function map(list, convert)
local result = {}
for index, item in ipairs(list) do
result[index] = convert(item)
end
return result
end
-- 现成的函数可以直接使用
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)