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

Easy way to see if something is in an array through value instead of index?

Asked by 5 years ago

When using a dictionary you can check if something is in it very easily like so:

local dict = {
    ["whatever"] = "yeh",
    ["stuff"] = "ok",
}

if dict["whatever"] then
    -- Do your stuff
end

As you can see it can be done very easily by seeing if the given dictionary contains that key, however with a typical array you cannot do that, you must do it by index.

local array = {"yeh", "ok"}

-- array["yeh"] will not work and will return nil
-- To find if a value is in it or not you have to run a for loop or know the index

-- By index
if array[1] then
    -- Do your stuff
end

-- By for loop

for _, v in pairs(array) do
    if v == "yeh" then
        -- Do your stuff
    end
end

This is not that big of a problem as I can easily make a function like this

local function findIn(value, array)
    for _, v in pairs(array) do
        if v == value then return true end
    end
    return false
end

I would simply like to know if there is a simpler way to do this.

0
There are no built-in functions for searching tables.  royaltoe 5144 — 5y
0
They're not arrays, they're dictionaries. Arrays contain numerical values, not string values. DeceptiveCaster 3761 — 5y
0
False, arrays can be any type of value, it's just a table with no keys. hitonmymetatables 50 — 5y

Answer this question