38 lines
793 B
Lua
38 lines
793 B
Lua
|
-- see if the file exists
|
||
|
local function file_exists(file)
|
||
|
local f = io.open(file, "rb")
|
||
|
if f then
|
||
|
f:close()
|
||
|
end
|
||
|
return f ~= nil
|
||
|
end
|
||
|
|
||
|
-- get all lines from a file, returns an empty
|
||
|
-- list/table if the file does not exist
|
||
|
local function lines_from(file)
|
||
|
if not file_exists(file) then
|
||
|
return {}
|
||
|
end
|
||
|
local lines = {}
|
||
|
for line in io.lines(file) do
|
||
|
lines[#lines + 1] = line
|
||
|
end
|
||
|
return lines
|
||
|
end
|
||
|
|
||
|
-- tests the functions above
|
||
|
local file = "input"
|
||
|
local lines = lines_from(file)
|
||
|
|
||
|
local total = 0
|
||
|
-- print all line numbers and their contents
|
||
|
for _, line in pairs(lines) do
|
||
|
for a, b in string.gmatch(line, "mul%((%d+),(%d+)%)") do
|
||
|
---@diagnostic disable-next-line: redefined-local
|
||
|
local a, b = tonumber(a), tonumber(b)
|
||
|
total = total + (a * b)
|
||
|
end
|
||
|
end
|
||
|
|
||
|
io.output():write(total)
|