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

Get name and not value of a multi-dimensional array?

Asked by
IXLKIDDO 110
9 years ago

So, in this scenario I have a multi-dimensional array that is in a module script. I have a localscript that is accessing that module script. It is correctly requiring and getting the sub-array, except it only gives the value and not the name. For example, if I had this array:

local Random = {
    Another = {
        Blank1 = 1,
        Blank2 = 2,
        Blank3 = 3,
    },
    Something = {
        Filled1 = 4,
        Filled2 = 5,
        Filled3 = 6,
    },
}

And I wanted to get the names of the sub-array's children. So for example, let's say I was checking if the values was 2, this is what I would do. Also, let's assume for all purposes that the local and everything else is already set-up so that it connects together.

for i, v in pairs(Random.Another) do
    if v == 2 then
        return v
    end
end

However, what I would want it to do is return Blank2, and not the value (or number). How would I do this?

0
Try printing out the index (i) instead and see what it comes up with. Spongocardo 1991 — 9y
0
It still outputs the value. IXLKIDDO 110 — 9y

1 answer

Log in to vote
1
Answered by
ImageLabel 1541 Moderation Voter
9 years ago
Edited 6 years ago
local Random = {
    Another = {
        Blank1 = 1,
        Blank2 = 2,
        Blank3 = 3,
    },
    Something = {
        Filled1 = 4,
        Filled2 = 5,
        Filled3 = 6,
    }
}

Your code is pretty accurate expect for the fact that you are returning the value instead of the key (index). In order to return the key, you would have to return (i -- as named in your snippet) instead of v

    for key,value in pairs(Random.Another) do
        if value == 2 then
            print(string.format([[value %s's key is %s]], value, key)) 
            return (key)    -- returns the key instead of value at key
        end
    end
--> value 2's key is Blank2
1
Welp, wished I noticed this sooner. Turned out that whenever I also tried doing somethng like return Random.Another[i] it was returning the value instead as well so I didn't think of this one. Thanks! IXLKIDDO 110 — 9y
0
Yup ImageLabel 1541 — 9y
Ad

Answer this question