lua-users home
lua-l archive

array index and modulo

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


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

AltStyle によって変換されたページ (->オリジナル) /