Jump to content

Pairs Loop


Recommended Posts

Hello, i'm having troube doing a pairs loop on a table. I'm doing the following

local test = {}

for i = 0, 9, 1 do
    test[i] = 4
end

for i, v in pairs(test) do
    print(tostring(i))
end

Which prints the following

[2022-07-02 11:46:19] INFO: 1
[2022-07-02 11:46:19] INFO: 2
[2022-07-02 11:46:19] INFO: 3
[2022-07-02 11:46:19] INFO: 4
[2022-07-02 11:46:19] INFO: 5
[2022-07-02 11:46:19] INFO: 6
[2022-07-02 11:46:19] INFO: 7
[2022-07-02 11:46:19] INFO: 8
[2022-07-02 11:46:19] INFO: 9
[2022-07-02 11:46:19] INFO: 0
The first element inserted into the table is the last in the loop, any explanation?
Link to comment
  • Moderators
7 hours ago, Modafinil said:

The first element inserted into the table is the last in the loop, any explanation?

First of all it is important to understand that tables(arrays) in Lua do not start at index 0, they start at index 1.

  • The pairs function does not always loop in order. (unreliable for looping in order)
  • The ipairs function does, but does not start at 0, it just skips it.

So if you want a loop starting at 0, the basic for loop is the best option to be honest.

 

 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...