-
-
Save balaam/4307004 to your computer and use it in GitHub Desktop.
Cyclic array access Lua vs C-languages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- | |
| -- 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