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:

1local dict = {
2    ["whatever"] = "yeh",
3    ["stuff"] = "ok",
4}
5 
6if dict["whatever"] then
7    -- Do your stuff
8end

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.

01local array = {"yeh", "ok"}
02 
03-- array["yeh"] will not work and will return nil
04-- To find if a value is in it or not you have to run a for loop or know the index
05 
06-- By index
07if array[1] then
08    -- Do your stuff
09end
10 
11-- By for loop
12 
13for _, v in pairs(array) do
14    if v == "yeh" then
15        -- Do your stuff
16    end
17end

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

1local function findIn(value, array)
2    for _, v in pairs(array) do
3        if v == value then return true end
4    end
5    return false
6end

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