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

How can I detect if something is in a table?

Asked by 6 years ago

I want to know how I can tell if an object is in a table. I have no clue where to start trying to figure this out, so I ask, is there any good way to do this?

0
You'd have to loop through the table and use 'IsA' to see if what was in the table was a part, or if you mean the bracket-thingies then `tbl['Thing']:IsA('BasePart')` TheeDeathCaster 2368 — 6y
0
tablename[item] ~= nil Bisoph 5 — 6y
0
Either, MyTable["APig"] or loop the table and see if the value is found. liteImpulse 47 — 6y

1 answer

Log in to vote
0
Answered by
Azarth 3141 Moderation Voter Community Moderator
6 years ago
Edited 6 years ago

There are a few ways with dictionaries.

local myTable = {['object'] = true}

-- Version 1
local function findMy1(object)
    if myTable[object] then 
        return true
    end
    return false
end

--[[ or shortened with

local function findMy1(object)
    return myTable[object]  -- > returns the value or nil if there isn't one
end

or using ternary operators

local function findMy1(object)
    return myTable[object] and true or false --> returns a bool
end

--]]


-- Version 2 - For loop
local function findMy2(object)
    for i,v in pairs(myTable) do 
        if i == object then 
            return true
        end
    end
    return false
end

-- Version 3 Using a metatable and the metamethod __index to
    -- give the table some function
setmetatable(myTable, {
    __index = function(self, key)
        print( string.format("%s was not found", key))
        return rawget(self, key)
    end
})

print ( findMy1('object'), findMy2('object'), findMy1('nilObject') )

Ad

Answer this question