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

Is it possible to use strings or instance names to index?

Asked by 9 years ago

Is there a way to use the name of a part to index one of its members like so?

game.Workspace._________.member = value -- Replace blank with some 'string'

e.g. If I had something like this:

function returnVariousNames() -- Produces various part names based on circumstances
    code
    code
    code
    return PART_NAME_STRING
end

Let's say I want to change the brick color of the part returned by the function.

game.Workspace._________.BrickColor.Color3 = 123

Is there a way to put the PART_NAME_STRING returned by the function into the 'path' to its color?

Sorry for the newbie question, I'm just wondering if there's a way to do it or if I need to find an alternate solution.

3 answers

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

When you say object.property, this is actually just sugar for using [] as in object["property"].

Thus if I wanted to my character in the workspace, I could say workspace["BlueTaslem"].

Since "BlueTaslem" is just a string expression, it makes sense that I could do this:

local name = "BlueTaslem"
local character = workspace[name]

Of course, you can also just use the :FindFirstChild function:

local character = workspace:FindFirstChild( name )

This has the benefit of not having issues with names conflicting with properties -- it will always pick the child.


As for you particular question about returnVariousNames -- usually you would return the part rather than the part's name -- that makes it harder for the function to be misused, and let's you do more changing of the function later (what if you wanted to move which model you were talking about? Or pull from different models?)

Ad
Log in to vote
0
Answered by 9 years ago

You don't actually need a function:

Game.Workspace["Part"].BrickColor = BrickColor.new("Really black")

Also, you cannot change the Color3 value of BrickColors.

Log in to vote
0
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
9 years ago

You don't need to get the entire path of the hierarchy whenever you want to access something. In a function, you can return the actual part itself.

function returnpart(part)
    return part
end
returnpart(workspace.Part).BrickColor=BrickColor.new("Bright red")

If you do want to get the path as a string, you can use the GetFullName method. It will not provide strictly correct syntax; it simply concatenates the ancestry with a "."

Answer this question