Skip to content

Instantly share code, notes, and snippets.

@balaam
Created December 16, 2012 13:01
Show Gist options
  • Select an option

  • Save balaam/4307004 to your computer and use it in GitHub Desktop.

Select an option

Save balaam/4307004 to your computer and use it in GitHub Desktop.
Cyclic array access Lua vs C-languages
--
-- In C style languages you can cyclically access elements of an array using the modulus operator
--
-- Lua-style psuedo code:
--
-- array = {'a', 'b', 'c', 'd'};
-- i = 0;
-- while true do
-- print(array[i % array.count()]);
-- i++;
-- end
--
-- Will print abcdadbcdadcd... for ever
--
-- Lua having arrays indexed from 1 makes this a pain in the ass
-- Here's how to translate the above from c-style language to Lua
--
array = {'a', 'b', 'c', 'd'}
i = 1
while true do
print(array[i % #array + 1])
i = i + 1
end
-- Will print bcdadbcdadcd...
-- Note that it starts from 'b' so that may require special case code for the above type of loop.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment