[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: array index and modulo
- From: Diego Nehab <diego@...>
- Date: Thu, 29 Mar 2007 03:23:43 -0400 (EDT)
Hi,
I once wrote a little metatable trick to make an array
circular. Here is what I used
-- circular array metatable
local function wrap(t, k)
return ((k-1)%(#t))+1
end
local lmt = {
__index = function(t, k)
if type(k) == "number" then
return rawget(t, wrap(t, k))
else
return nil
end
end
}
-- turns a table into a circular array
function circular(t)
return setmetatable(t, lmt)
end
Now you can do something like this
a = circular{1, 2, 3, 4}
for i = 1, 10 do
print(a[i])
end
1
2
3
4
1
2
3
4
1
2
[]s,
Diego.