# Define an incremental counter with Lua

I would like to receive a suggestion for this example. Really, it is more a question related to Lua scripting.

## Minimal working example

\documentclass{beamer}

\directlua{dofile("timer.lua")}

\providecommand{\interval}[1]{
\directlua{
tex.print("\string\\textbf{Time estimation}: " .. #1 .. " seconds.".. "\string\\hfill" .. "$t\string\\in" .. "\string\\left[" .. start .. "," .. difference(#1) .. "\string\\right]" .. "$" .. " min.")
}
}
\begin{document}

\frame{\interval{60}}

\frame{\interval{240}}

\end{document}


### timer.lua

#!/usr/bin/lua

function trunc(num, digits)
local mult = 10 ^ (digits)
return math.modf(num * mult) / mult
end

start = 0

function difference(increment)
increment = increment + start
diff = (increment - start)/60
return trunc(diff, 2)
end


I'm working with

• Lua 5.4.3 Copyright (C) 1994-2021 Lua.org, PUC-Rio
• This is LuaHBTeX, Version 1.12.0 (TeX Live 2020/Arch Linux).

### Output desire

I would like to have the acummulation of times, i.e,

• from the first slide \interval{increment1} and put Time estimation: increment1 seconds. $t\in\left[start, start+increment1\right]$.
• and the second slide \interval{increment2} and put Time estimation: increment2 seconds. $t\in\left[start+increment1, start+increment1+increment2\right]$. The default value for start is zero.

Like a recurrence

$$S_{n}=S_{n-1}+S_{n-2},\forall n\geq2.$$

Thanks.

## 1 Answer

How about

--timer.lua:
sum = 0

function difference(increment)
oldsumstr = string.format("%.2f",sum/60)
sum = sum + increment
sumstr = string.format("%.2f",sum/60)
return oldsumstr,sumstr
end


and then:

\providecommand{\interval}[1]{
\directlua{
local oldsumstr,sumstr = difference(#1)
tex.print("\string\\textbf{Time estimation}: " .. #1 .. " seconds." ..
"\string\\hfill" .. "$t\string\\in" .. "\string\\left[" .. oldsumstr .. "," .. sumstr .. "\string\\right]" .. "$" .. " min.")
}
}


This should yield the desired result.

• Very good @frafl, works very \frame{\interval{60}} \frame{\interval{240}} \frame{\interval{600}} \frame{\interval{55}}. Thank you. Apr 27, 2021 at 3:36