RosettaCodeData/Task/Search-a-list/Pluto/search-a-list.pluto
2026-04-30 12:34:36 -04:00

25 lines
871 B
Text

local function search(haystack, needle)
local indices = {}
for i = 1, #haystack do
if haystack[i] == needle then indices:insert(i) end
end
local c = #indices
if c == 0 then error("Needle not found in haystack.") end
local t = (c == 1) ? "time" : "times"
print($"The needle occurs {c} {t} in the haystack.")
if #indices == 1 then
print($"It occurs at index {indices[1]}")
else
print($"It first occurs at index {indices[1]}")
print($"It last occurs at index {indices:back()}")
end
print()
end
local haystack = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"}
print($"The haystack is: \n{haystack:concat(", ")}\n")
local needles = {"Wally", "Bush", "Zag", "George"}
for needles as needle do
print($"The needle is {needle}.")
search(haystack, needle)
end