Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why does doing this not print anything when it obviously prints something when I index by num?


local Tab = {
}

for i,v in pairs(workspace:GetChildren()) do
Tab[#Tab + 5] = v.Name
end

for i  = 1,#Tab do
	print(Tab[i]) -- How come this don't print anything it should index 5 also  but returns nothing 
end

print(Tab[5] ) -- Prints script

Tab[i] should index 5 but i dont think its doing that

1 answer

✓ Accepted answer

For the issues you've come across, it may be a little hard to explain through words alone. So, I took the liberty of showing you the process that's occurring during the iteration of workspace, through some debug statements.

local workspace = {1,2,"Hello", "there", "I'm", "Feahren",3,4} -- Mocking workspace

local tab = {}

for i,v in pairs(workspace) do
    print("Index: "..i.." Value: "..v.." Table Length: "..#tab)
    tab[#tab+5] = v -- assuming it'll place v at index 5 from 0
    print(tab[i])
end

After applying the lines to help us parse the data, I was given these results. Let's take a look.

Index: 1 Value: 1 Table Length: 0
nil -- Copied value from workspace
Index: 2 Value: 2 Table Length: 0
nil
Index: 3 Value: Hello Table Length: 0
nil
Index: 4 Value: there Table Length: 0
nil
Index: 5 Value: I'm Table Length: 0
I'm -- Approved | Hypothesis correct
Index: 6 Value: Feahren Table Length: 0
nil
-- Index 6 also shows nil (recursively rejected)

From analyzing the data, It's conclusive that all values except with pardon from the fifth index in workspace, is not approved. All the while showing that the table length, even afterwards, remains 0; this is why the for i loop isn't functioning, because the iteration input translates to the following:

for i = 1,0 do -- It's being told to loop by 1 out of 0 times; it will stop immediately.

Conclusion

From what I've been able to gather, using the syntax tab[#tab+5], it appears to create a reserved slot within the table at the specified numerical index, look it like this:

tab[#tab+a] a as the reserve point.

Altogether—due to the restrictive principles that follow with said syntax—all other processed values will be forced to be stored within the reserved slot, causing them to overlap and override, until the final value is iterated, which will be the static result.


I hope this explains everything, and that you understood everything I talked about, if you have any further questions, don't be afraid to ask. However, all I can say is that, to fix your issue, you must simply use another form of referencing the placement of the iterated values from workspace to tab.

This discussion is preserved as it was. New answers, comments, and votes are closed.