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

For some reason it says that my table is a nil value?

Asked by
JoneXI 51
5 years ago

Hello, The script below... For some reason it says that clone is a nil value? Although it prints that 4 items insterted into the table... Any ideas

01for i,v in pairs(storage.items:GetChildren()) do
02    if v:IsA("Tool") then
03        table.insert(items, v)
04    end
05end
06 
07print(#items.." Items inserted into the table")
08    local clone = items:Clone()
09    clone.Parent = player.Inventory
10    print("Cloned")
11end)

Thank you.

2 answers

Log in to vote
2
Answered by
Rinpix 639 Moderation Voter
5 years ago

A table isn't an instance that you can just call :Clone() on.

If you want to clone a table, do this:

01local first_table = {5, 15, 20, 25, 30}
02 
03-- Let's say I want to clone this table ^^
04-- To do that, we need to create another table and iterate through the original:
05 
06local second_table = {}
07 
08for i = 1, #first_table do
09    second_table[i] = first_table[i]
10end

Now, second_table has all of the values in first_table.

And if you want to put each of their values into a player's inventory, you need to iterate through the table again.

1for i = 1, #second_table do
2    second_table[i].Parent = player.Backpack
3end

I know that second_table contains only numbers, but the same thing can be done with a table that contains tools.

Also, with tables, you can't just do this to clone tables:

1test_table_1 = {5, 10, 15, 20, 25, 30}
2test_table_2 = test_table_1

What that does is simply creates another variable for the exact same table in memory. You're not cloning the first table, you're just creating another reference for it.

1test_table_1[1] = 5
2test_table_2[1] = 10

Since test_table_1 and test_table_2 are referencing the same table in memory, both of these lines are modifying the same index of the same table.

1print(test_table_1[1]) -- prints 10
2print(test_table_2[1]) -- prints 10

Since we changed the first index of the same table to 10 on the last line, and both variables reference the same single table in memory, both of these lines produce the same result.

1
Thank you, good explanation. JoneXI 51 — 5y
Ad
Log in to vote
1
Answered by
N43FGXL 169
5 years ago

When you say items:Clone() on line 8, you need to loop through the table and clone the items to the player's inventory individually.

1for i,v in pairs(items) do
2    local clone = v:Clone()
3    clone.Parent = player.Inventory
4    print("Cloned")
5end

I don't think you can just clone the table and put that in the player's inventory/backpack.

0
This answer more clearly addresses a misunderstanding OP had about tables, which is that you can't just put a table into a player's backpack. Nice answer :) Rinpix 639 — 5y
1
Thank you. JoneXI 51 — 5y

Answer this question