--Lua 5.4.7 local File = io.open("input.txt", "r") if not File then print("File not found") return end local NUMBER_MATCH = "^%d+$" local Separators = { ",", } local ContainerPairs = { -- why do I bother ["("] = ")" } local Instructions = { -- refer to the comment above ["mul"] = function(a, b) return a * b end, } local function t_find(t, v) for i, whyisthisnotstd in next, t do if whyisthisnotstd == v then return true, i, whyisthisnotstd end end end local Results = {} local InputString = File:read("a") local Offset = 1 while Offset <= #InputString do for InstructionName, Evaluator in next, Instructions do local Extent = Offset + #InstructionName - 1 local SubString = InputString:sub(Offset, Extent) local LeftArgument, RightArgument if SubString == InstructionName then for PairStart, PairEnd in next, ContainerPairs do if InputString:sub(Extent + 1, Extent + #PairStart) == PairStart then local Anchor = Extent + #PairStart + 1 local Offset2 = 1 while not (LeftArgument and RightArgument) do local CurrentOffset = Anchor + Offset2 local CurrentLeftNumber = InputString:sub(Anchor, CurrentOffset - 1) if not CurrentLeftNumber:match(NUMBER_MATCH) then break end if t_find(Separators, InputString:sub(CurrentOffset, CurrentOffset)) then LeftArgument = CurrentLeftNumber for Offset3 = 1, #InputString - CurrentOffset do local CurrentRightNumber = InputString:sub(CurrentOffset + 1, CurrentOffset + Offset3) if not CurrentRightNumber:match(NUMBER_MATCH) then break end if InputString:sub(CurrentOffset + Offset3 + 1, CurrentOffset + Offset3 + 1) == PairEnd then RightArgument = CurrentRightNumber break end end end Offset2 = Offset2 + 1 end end end if LeftArgument ~= nil and RightArgument ~= nil then local EvaluationResult = Evaluator(tonumber(LeftArgument), tonumber(RightArgument)) table.insert(Results, EvaluationResult) end end end Offset = Offset + 1 end local Sum = 0 for _, Result in next, Results do Sum = Sum + Result end print(Sum)