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

Whats the difference between using brackets to add to table and using table.insert?

Asked by 5 years ago

So today I came upon a different way to insert things into table which utilized square brackets

I don't fully understand what I should use and why they both do the same thing is there any difference? or any reason I should use one over one?

local Way1 = {}

for i,v in pairs(game.Workspace:GetChildren()) do
Way1[#Way1 + 1] = v.Name


end

for _,v in pairs(Way1) do
    print(v)
end





local Way2 = {}

for _,v in pairs(game.Workspace:GetChildren()) do
    table.insert(Way2,v)

end


for i,v in pairs(Way2) do
    print(v)
end

1 answer

Log in to vote
0
Answered by
DanzLua 2879 Moderation Voter Community Moderator
5 years ago

Why would you want to perform some math to set that index when you could simply insert it at the next available slot. Unless you need to set that value to a specific spot there is no point in not using insert().

I'm not saying you should never use [], I use them all the time for specifics, but for this use case insert works just fine.

Ad

Answer this question