function MovingAverage(reg, filter) local Q_DEPTH , queue_fill, av_sum = 10 , R(filter .. "_fill"), R(filter .. "_sum") local in_value, tmp_var, out_value = R(reg), 0, 0 -- read input and initialize some vars if (queue_fill < Q_DEPTH) then -- queue not filled yet av_sum = av_sum + in_value -- accumulator queue_fill = queue_fill + 1 -- inc. index else -- now the queue full tmp_var = av_sum / Q_DEPTH -- calc. weight of the one element of the queue av_sum = av_sum - tmp_var + in_value -- subtract it and add new input value end if (queue_fill == Q_DEPTH ) then -- if filled out_value = av_sum / Q_DEPTH -- calc. as current accumulator / queue lentgh, moving average else out_value = av_sum / queue_fill -- not filled then mean average end -- remember state W (filter .. "_sum", av_sum) W (filter .. "_fill" , queue_fill) return out_value end -- MovingAverage