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

How come this table.remove line won't work?

Asked by
mnaj22 44
8 years ago
table.remove(selection, Axe)

I made a table called selection and I have already inserted Axe into the table.

The error it says is

13:01:08.879 - Players.Player.Backpack.Script:12: bad argument #2 to 'remove' (number expected, got Object)

3 answers

Log in to vote
1
Answered by 8 years ago

That's because table.remove is a function that removes an element from an array, based on it's second argument (the index number)

I'd go more in depth, but I've already given a quite detailed explanation about this before, that you can find here: https://scriptinghelpers.org/questions/22565/tableinsert-and-tableremove#26210

Let me know if you have any questions.

Ad
Log in to vote
3
Answered by
BlackJPI 2658 Snack Break Moderation Voter Community Moderator
8 years ago

The function remove in the table library takes two arguments, an array and (optionally) an integer.

If just table.remove(table) is called, it will remove what ever is at the last index in that array. If you specify an integer, it will remove what ever is in the table at that index and shift everything else down.

But you are passing it an Object, which it doesn't accept as an argument type. Instead, we have to write a loop of some kind to find the Object in the array and retrieve its index:

function removeObject(array, object)
    local index
    for i, value in next, array do
        if object == value then
            index = i
        end
    end
    table.remove(array, index)
end

This function will remove the last occurrence of that exact object (won't delete a clone of the object).

Log in to vote
0
Answered by
DevSean 270 Moderation Voter
8 years ago

table.remove does not work that way. table.remove removes the value at a specific position.

For example:

tableOfStuff = {"pos1", "pos2", "pos3", "pos4"}
table.remove(tableOfStuff, 2) -- will remove "pos2" from the table

To remove an object (Like your axe) you can do the following:

for i, object in pairs(selection) do
    if (object == Axe) then
        table.remove(selection, i)
        break -- add a break to only remove one object
    end
end

Wiki article

Answer this question