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

how do I find a value in a table by its name?

Asked by 3 years ago

I have a table with models named redtycoon, bluetycoon and greentycoon. how would I find them by name? I tried this and it doesn't work. .Name doesn't work either

for i,v in pairs (tycoons) do



    if i == "RedTycoon" then
            print("red")
        end
        if i == "BlueTycoon" then
            print("blue)
        end

        if i.Name == "GreenTycoon" then
        print("green")
end


        end
0
i is index, v.Name will give you the name of the thing you want (if the things stored in tycoons are instances and not strings) AlexTheCreator 461 — 3y
0
if you're storing these things in a dictionary ( e.g. local tycoons = { ["red"] = game.workspace.redtycoon } ... you can do local redtycoon = tycoon[red] to set the variable to equal the same instance as is stored in the dictionary... AlexTheCreator 461 — 3y
0
Use if v = not if I=, v is what you’re looking for. WideSteal321 773 — 3y

1 answer

Log in to vote
1
Answered by 3 years ago

In this case, "i" stands for the index (or key!) of the value (v) you are looking for. Since this is a dictionary, there are a couple ways to reference them (but I can't list all of them as Roblox has built-in API to search dictionaries within the hierarchy of the game)

This means you can do this:

for i, v in pairs(tycoons) do
    print(i)
end

But I'm assuming you want to access a specific tycoon and not iterate through each one. In that case, you can do this for dictionaries, also known as tables that use non-numerical indices (which include, but are not limited to, Enum values, strings, table reference pointers, userdata, etc):

local tycoons = {}
tycoons["RedTycoon"] = "Hello."
print(tycoons["RedTycoon"]) -- I recommend this for indices that include spaces.
print(tycoons.RedTycoon) -- This is nearly the same exact thing as the above, except you cannot have indices start with a digit.

-- OUTPUT:
-- >>Hello.
-- >>Hello.

You search for them just like you do with normal tables, except the value type is different.

Ad

Answer this question