lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


function nextData()
     currentData = (currentData+1) % (#data)              --gives [0, #data-1]
     return data[currentData+1]
end

???

________________________________________
From: lua-bounces@bazar2.conectiva.com.br [lua-bounces@bazar2.conectiva.com.br] On Behalf Of Wesley Smith [wesley.hoke@gmail.com]
Sent: Thursday, March 29, 2007 12:07 AM
To: Lua list
Subject: array index and modulo

This is a very simple problem, but I'm failing to find an elegant
solution.  I have an array of data that I'm treating as a circular
buffer.  Typically I use modulo to wrap the index to the range of the
buffer, but since Lua arrays start from 1 (and I want to follow this
convention), the modulo operator is not really useful.

for example.

given

local numData = 10
data = {}
for i=1, numData do
     data[i] = newData()
end
currentData = 0

what is a good solution for this function:

function nextData()
     currentData = (currentData+1) % (#data)              --gives [0, #data-1]
     return data[currentData]
end


--I could do this, but is there a better solution?
function nextData()
     currentData = currentData+1
     if(currentData > #data)  currentData = 1   end
     return data[currentData]
end

thanks,
wes