lua-users home
lua-l archive

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


currentData = (currentData + 1) % (#data) + 1?

Tomas

On Thu, 29 Mar 2007 00:07:44 -0700
"Wesley Smith" <wesley.hoke@gmail.com> wrote:

> 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

Attachment: pgpOIydEz1app.pgp
Description: PGP signature