What would these statments be used for and how would I go about using them?
Those words that you pointed out are used in iterating a table. Those syntaxes will commonly be used when using a generic for loop.
v
is short for value. i
is short for index.
Let's take a look at a generic for loop
local tbl = {5,10,"hi"} -- We need a table to iterate for i,v in pairs(tbl) do -- I will explain pairs() in more detail. For now, you need to know that you need this function for using generic for loops -- code -- end
i is our index. You may have seen this letter in a number for loop
for i = 1,5,1 do end -- i is our counter
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.
local tbl = {5,10,"hi"} for i,v in pairs(tbl) do print("Current index",i) print("Current value",v) print() -- Just to make the iteration result looks more clean end --[[ Output: Current index 1 Current value 5 Current index 2 Current value 10 Current index 3 Current value hi --]]
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.
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
local tbl = {5,10,"hi"} for i,v in pairs(tbl) do print("Current index",i) print("Current value",v) print() end
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()
.
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
local tbl = {5,10,nil,"hi"} for i,v in ipairs(tbl) do print("Current index",i) print("Current value",v) print() end --[[ Output: Current index 1 Current value 5 Current index 2 Current value 10 --]]
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
local tbl = {5,10,"hi"} for i,v in next,tbl do print("Current index",i) print("Current value",v) print() end