What are those terms?
Those words that you pointed out are used in iterating a table. Those syntaxes will commonly be used when using a generic for loop.
What is i,v and in?
v
is short for value. i
is short for index.
Let's take a look at a generic for loop
2 | for i,v in pairs (tbl) do |
i is our index. You may have seen this letter in a number for loop
i is technically a counter. It says the index of the value we are on
v is the value the generic for loop is on.
EDIT: i,v can be changed to anything(i.e hi,lol; yes,no etc.; however, it is nice to use i,v(index,value) or k,v(key,value) since they are usually the most common letters to use when working with generic for loop iteration)
Let's make a simple generic for loop that prints the values.
01 | local tbl = { 5 , 10 , "hi" } |
02 | for i,v in pairs (tbl) do |
03 | print ( "Current index" ,i) |
04 | print ( "Current value" ,v) |
in
is technically a syntax you need to type down. I don't think you should really care about its role in a generic for loop. I think in
is just a syntax that has something to do with what studio has behind the scenes.
What is pairs?
As you might have noticed, pairs()
is one of the built-in functions.
pairs()
is a function that returns the next()
function and the table you are iterating.
Let's take a look at our last example
2 | for i,v in pairs (tbl) do |
3 | print ( "Current index" ,i) |
4 | print ( "Current value" ,v) |
pairs()
's argument is the table it needs to iterate.
The pairs()
function iterates a table without caring if something is nil or not. This leads me to the next iterating function, ipairs()
.
What is ipairs()?
ipairs()
is another built-in function like pairs()
It returns the function next(), the table you are iterating, and an integer. This integer returns if the value the generic for loop is on, is nil or not(I am not quite sure though, so don't quote me on that). ipairs()
stops the for loop when it encounters a nil value
01 | local tbl = { 5 , 10 , nil , "hi" } |
02 | for i,v in ipairs (tbl) do |
03 | print ( "Current index" ,i) |
04 | print ( "Current value" ,v) |
ipairs()
can be useful when you want to make sure every value is not nil value and you are not sure about it.
NOTE: There is another way to iterate a table without using pairs() and ipairs(). This will do the same thing
3 | print ( "Current index" ,i) |
4 | print ( "Current value" ,v) |