local numbers = {2, 3, 5, 7, 11, 13, 17}
-- No indexOf: a loop returns the position
local function index_of(t, value)
for index, item in ipairs(t) do
if item == value then
return index
end
end
return nil
end
local index5 = index_of(numbers, 5)
-- index5 = 3
local contain5 = index5 ~= nil
-- contain5 = true
-- Not found is nil, not an error
local index10 = index_of(numbers, 10)
-- index10 = nil
-- First match by condition
local first_over7
for _, number in ipairs(numbers) do
if number > 7 then
first_over7 = number
break
end
end
-- first_over7 = 11
-- Count the matches
local values = {1, 9, 8, 3, 1, 6, 71}
local count_of_1 = 0
for _, value in ipairs(values) do
if value == 1 then
count_of_1 = count_of_1 + 1
end
end
-- count_of_1 = 2
print("index5 = " .. index5)
print("contain5 = " .. tostring(contain5))
print("index10 = " .. tostring(index10))
print("first_over7 = " .. first_over7)
print("count_of_1 = " .. count_of_1)