function P_TRIG(var, previous) -- detect rising or falling state of the register var -- false for nil input -- previous regoster value stored in previous register (id or alias) DEBUG("P_TRIG was called with this " .. var .. " " ..previous) local curVar = R(var) if not curVar then return false end local prevVar = R(previous) ; DEBUG(" p_trig " .. curVar .. " " .. prevVar) W(previous, curVar) if (curVar ~= prevVar) then if (curVar > prevVar) then return "positive" else return "negative" end end return false -- nothing happened end -- P_TRIG -- usage example function main(userId) if P_TRIG("pulseId", "pulsePreviousValue") == "positive" then local counterNewValue = R("counterId") + 1 W("counterId", counterNewValue) end end -- Another version using global callable object P_TRIG = setmetatable({}, -- callable objects like P_TRIG_FOR_COUNTER ... {__call = function(self, regToTrack) -- init section local newValue = R(regToTrack) if (not self.previousValue) then self.previousValue = newValue return false end -- main logic local result if (self.previousValue ~= newValue) then if (newValue > self.previousValue) then result = 'rise' else result = 'fall' end else result = false end self.previousValue = newValue -- store previous value return result end } ) -- usage function main(userId) local ptrig = P_TRIG("testReg2") -- only one call in scan is correct! if (ptrig == "rise") then DEBUG("rise detected!") elseif (ptrig == "fall") then DEBUG("fall detected!") else DEBUG("nothing detected!") end end