4FipS.com Forums

A simple circular buffer with reverse iterator (Lua)

A simple circular buffer with reverse iterator (Lua)

Posted: Wed Nov 23, 2016 10:22 pm

by FipS

This is just a small code snippet showing a simple circular buffer with reverse iterator that I've coded up for my forthcoming IoT NodeMcu-based project. Its purpose is to provide fixed and efficient storage for data coming from sensors, so in my case it basically represents history of N most recent values with additional convenience of the reverse iterator for easy FIFO access. I haven't coded in Lua for some time, so it was quite refreshing to come up with this. I especially like how iterators can make use of closures for tracking state, which makes the implementation pretty simple end easy to read. What I don't like about Lua that much is the infamous 1-based indexing, which feels unnatural to me, especially when dealing with modular arithmetic for index wrapping.