Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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?

2 comments

0

Try printing out the index (i) instead and see what it comes up with.

0

It still outputs the value.

1 answer

✓ Accepted answer
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

2 comments

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!

0

Yup

This discussion is preserved as it was. New answers, comments, and votes are closed.