Joshua Watts
Joshua Watts

Reputation: 1

Is there a way in lua to do this Parent.Parent.{{VAR}}.child

I'm currently working on a Roblox game for a school assignment, so I'm making a basic tycoon game with a function that works like this:

game.Workspace.Gate.Touched:Connect(function()
    game.Workspace.Path.Transparency = 0
    game.Workspace.Path.CanCollide = true
    game.Workspace.Fence.Transparency = 0
    game.Workspace.Fence.CanCollide = true
end

But I was wondering if there is a way to make this function more practical in the long term to make it something like:

game.Workspace.Gate.Touched:Connect(function({{myVar}})
    game.Workspace.{{myVar}}.Transparency = 0
    game.Workspace.{{myVar}}.CanCollide = true
end

I honestly just started Lua today but picked it up very quickly, but I guess there are plenty of things I missed. Thanks in Advance.

Upvotes: 0

Views: 439

Answers (1)

Felix
Felix

Reputation: 2386

This

game.Workspace.Path.Transparency = 0

and this

game["Workspace"]["Path"]["Transparency"] = 0

does exactly the same. You can also mix both:

game.Workspace["Path"].Transparency = 0

The difference is only in syntax. The first only allows you to access keys which are valid identifiers and looks a bit "cleaner". The second allows you to use any variable or constant.

So this code:

game.Workspace.Gate.Touched:Connect(function(myVar)
        game.Workspace[myVar].Transparency = 0
        game.Workspace[myVar].CanCollide = true
end

is completely fine.

Upvotes: 2

Related Questions