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

How to get position of something in a table?

Asked by 9 years ago

So I'm putting brick name into a table for this thing I'm scripting. I'm not sure how to get the position so that I can use table.remove I would love to just use code like this

table.remove(SelectedBricks, Brick.Name)

If possible, Also. SelectedBricks is the name of the table. The only thing I can "search" the table by is the Brick.Name

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

There is no built in function to find the place of an object inside of a table.

Lua is missing a few such useful functions that most languages provide by default, I'm not sure why.

In any case, defining a function ourselves to do this is easy:

function indexOf(tab, value)
    for key, v in pairs(tab) do
        if v == value then
            return key;
        end
    end
end

This is one possible definition of your table. Note that it only returns the first instance of a value in your table, and not all of them.

In addition, it searches non-numeric keys as well, which may not be what you want.

This would be used as:

table.remove(tab, indexOf(tab, Brick.Name))

to remove Brick.Name from tab.

Ad

Answer this question