|
| 11 Mar 2012 02:39 PM |
Why is this "some-what" order correctly?
Output:
Stair 1 Stair 2 Stair 3 Stair 4 Stair 5 Stair 6 Stair 8 Stair 7 Stair 10 Stair 9 Stair 11 Stair 12 Stair 14 Stair 13 Stair 15 Stair 16
Code:
local Positions = {}
for _, v in pairs(script.Parent:GetChildren()) do if string.find(v.Name, "Stair") then table.insert(Positions, v.Name:match("%d+"), v.Name) end end
for _, v in pairs(Positions) do print(v) end |
|
|
| Report Abuse |
|
|
| |
|
SDuke524
|
  |
| Joined: 29 Jul 2008 |
| Total Posts: 6267 |
|
|
| 11 Mar 2012 03:11 PM |
> v.Name:match("%d+")
That should return a string, not a number. |
|
|
| Report Abuse |
|
|
NXTBoy
|
  |
| Joined: 25 Aug 2008 |
| Total Posts: 4533 |
|
|
| 11 Mar 2012 03:30 PM |
Couple of things. Firstly, you can use `v.Name:find("Stair")` instead of `string.find(v.Name, "Stair")`. Better yet though, you can do the entire thing in one statement:
local number = v.Name:match("Stair (%d+)")
Also, `table.insert(t, i, v)` is not what you want here. Insert with 3 arguments is for when you want to shift all the other elements along one. Simply using an index will suffice.
local stairs = {} for _, child in pairs(script.Parent:GetChildren()) do local number = v.Name:match("Stair (%d+)") if number then stairs[number] = child end emd for _, stair in ipairs(stairs) do print(v) end
As a side note, if order is important, then favor ipairs over pairs when iterating. |
|
|
| Report Abuse |
|
|
NXTBoy
|
  |
| Joined: 25 Aug 2008 |
| Total Posts: 4533 |
|
|
| 11 Mar 2012 03:32 PM |
Whoops, SDuke is right. Needs a number conversion. Either use `tonumber`, or just add 0. Fixed below:
local stairs = {} for _, child in pairs(script.Parent:GetChildren()) do local number = v.Name:match("Stair (%d+)") if number then stairs[number + 0] = child end emd for _, stair in ipairs(stairs) do print(v) end |
|
|
| Report Abuse |
|
|
|
| 11 Mar 2012 03:33 PM |
As an expansion on NXTBoy's side note: Pairs is not guaranteed to go through the table in order of indices. |
|
|
| Report Abuse |
|
|