Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Can someone explain to me/help me what. for i,v in pairs do. Does? Help me please :D

Asked by 5 years ago

Hey, I'm still not 100% sure what "for i,v in pairs do" does or how to use it. Can someone explain it to me.

1 answer

Log in to vote
4
Answered by 5 years ago
Edited 5 years ago

Oh God! It was a pain in the butt for me too! Even though it is very easy, it took my while. Alright so, I'll try to describe as easy as I can.

In every programming language including Lua, there are arrays(Or tables) and those tables have two main things. An index and a value(This is where i and v comes from. i stands for index, v stands for value but you can change those as you wish.)

You can reach value by using TableName[IndexValue] easily but most of the times you will encounter with tables that you don't know what index is but you still have to reach it. Array indexs aren't always straight like 1,2,3, they can be like 1,5,9,"lol","xd",333. That's where In Pairs comes.

So, let's create a table first.

local OurTable = {} --First, creating an empty table.
OurTable["EnomphiaMoney"] = 500 --Equaling index "EnomphiaMoney" to 500
OurTable["superalp1111Money"] = 1337 --Equaling index "superalp1111Money" to 1337

Now we can't just reach arrays with a NORMAL for loop. Normal for loops are loops that counts from a starting value to ending value with an increment. That's why we are going to use in pairs. I will tell it more detailed after writing the code.

for a,b in pairs(OurTable) do --As I said, you can change variable names. I prefer a and b
    print("Value for "..a.." index is: "..b)
end)

So basically, this prints index and the value that table has for that index. Output would be:

Value for EnomphiaMoney index is: 500
Value for superalp1111Money index is: 1337

I hope I could tell it good! It's very useful thing for tables.

Note: If this helped, can you upvote and accept as answer please? Upvote is very important for me, thanks <3

Ad

Answer this question