[Tutorial] Math and Lua Tips for BoI Modding⚓︎
Lua Tips⚓︎
Iterate over tables⚓︎
The best way to iterate over a table is by using the ipairs() or pairs() functions.
ipairs⚓︎
ipairs() allows you to iterate over the table, providing the index of the element and the element value. The function does only work for tables without any keys!
1 2 3 4 | |
Result
1 2 3 4 | |
pairs⚓︎
pairs() allows you to iterate over the table, providing the key of the element and the element value. The function should be used for tables with keys defined!
Note: Tables with keys are always unsorted.
1 2 3 4 | |
Result
1 2 3 4 | |
Number of Table entries⚓︎
Tables without keys⚓︎
For tables that don't have keys, you can use a simple # (Hashtag) in front of the table name to get the number of table entries.
1 2 | |
Tables with keys⚓︎
For tables that have keys, you need to count the number of entries with a loop to get the number of table entries.
1 2 3 4 5 6 | |
0 vs 1 based indexing⚓︎
0-based indexing will loop over a collection from 0 to length-1.
1-based indexing will loop over a collection from 1 to length.
Isaac modding can be confusing because you could run into both of these scenarios within the same code file.
CppContainer collections⚓︎
These collection types are generated by the game and use 0-based indexing.
1 2 3 4 5 | |
Lua tables⚓︎
Lua tables without keys use 1-based indexing. You can create your own tables or they could be generated by the game.
Note: This is for demonstration purposes. It's easier to use ipairs() in this case.
1 2 3 4 5 | |
Randomness⚓︎
There's two ways to grab random items with the modding API.
RNG():RandomInt(max) will give you a number from 0 to max-1.
math.random(max) will give you a number from 1 to max.
1 2 3 4 5 6 7 | |
Math tips⚓︎
Modulo (Remainder of a division)⚓︎
The Modulo operator % is a very powerful tool in programming, because it can save you lots of code. It basically returns the whole number that would remain from a division by a given number.
Usage⚓︎
1 | |
Examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
Floor Division⚓︎
While not particularly useful and easily replaceable by using math.floor, floor division can help with simplifying and organising code. It works similarly to the regular division operator, but rounds the result down to the nearest integer.
Usage⚓︎
1 | |
1 | |
-11//5 will return -3 whereas 11//5 will retun 2. This makes it so making a number negative can generate different results if you do so before or after using the Floor Quotient operator.
Examples
1 2 3 4 5 6 7 8 | |
Integer vs Float⚓︎
type(x) will return "number" if the variable is a number, but it won't tell you if it's an integer or float.
math.type(x) will return "integer" or "float", or nil if it's not a number.
1 2 3 4 5 6 | |