Created
September 30, 2019 08:33
-
-
Save nagolove/b4c82a55fb11f2e25c0a4222cb555c4e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 1. Перебор с удалением. | |
-- Что не так в данном коде, почему он падает с ошибкой и как его можно исправить? | |
-- Предложить два способа решения | |
local tbl = {0, 1, 2, 3, 4, 4, 3, 2, 1} | |
for i = #tbl, 1, -1 do | |
local v = tbl[i] | |
if i % 2 == 0 then | |
table.remove(tbl, i) | |
end | |
end | |
print(table.concat(tbl, " ")) | |
---------------------------------------------- | |
local tbl = {0, 1, 2, 3, 4, 4, 3, 2, 1} | |
local t = {} | |
for i = 1, #tbl do | |
if i % 2 ~= 0 then | |
t[#t + 1] = tbl[i] | |
end | |
end | |
tbl = t | |
print(table.concat(tbl, " ")) | |
-- 2. Множественные аргументы | |
-- Переделать этот код так, чтобы внутри функции не создавалось никаких таблиц | |
function foo(...) | |
-- local args = {...} --< убрать эту таблицу | |
local summ = 0 | |
for i = 1, select("#", ...) do | |
summ = summ + select(i, ...) | |
end | |
return summ | |
end | |
print(foo(10, 20, 30, 40, 50)) | |
-- 4. Итераторы | |
-- Написать итератор аналогичный ipairs, который проходит по таблице в обратном порядке | |
-- Пример: | |
function ripairs(tbl) | |
local i = #tbl + 1 | |
return function() | |
i = i - 1 | |
if i >= 1 then return i, tbl[i] end | |
end | |
end | |
local tbl = {10, 20, 30, 40, 50} | |
for i, v in ripairs(tbl) do | |
print(i, v) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment