Modafinil Posted July 2, 2022 Share Posted July 2, 2022 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 IIYAMA Posted July 2, 2022 Moderators Share Posted July 2, 2022 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
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now