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
4 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

for i,v in pairs(storage.items:GetChildren()) do
    if v:IsA("Tool") then
        table.insert(items, v)
    end
end

print(#items.." Items inserted into the table")
    local clone = items:Clone()
    clone.Parent = player.Inventory
    print("Cloned") 
end)

Thank you.

2 answers

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

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

If you want to clone a table, do this:

local first_table = {5, 15, 20, 25, 30}

-- Let's say I want to clone this table ^^
-- To do that, we need to create another table and iterate through the original:

local second_table = {}

for i = 1, #first_table do
    second_table[i] = first_table[i]
end

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.

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

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:

test_table_1 = {5, 10, 15, 20, 25, 30}
test_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.

test_table_1[1] = 5
test_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.

print(test_table_1[1]) -- prints 10
print(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 — 4y
Ad
Log in to vote
1
Answered by
N43FGXL 169
4 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.

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

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 — 4y
1
Thank you. JoneXI 51 — 4y

Answer this question