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

How to use variables to refer to an instance?

This is a test script:

wchildren = game.Workspace:GetChildren()
for a, b in ipairs(wchildren) do
	game.Workspace.b:Destroy()
end

However, the game seems to be looking for an object named b instead of one with the name of the variable b.

b is not a valid member of Workspace

Edited: changed code

2 comments

0

The problem is that b itself is the instance you are looking for. Try print(b.Name) instead and you'll see what I mean. For better coding practices do local wchildren = workspace:GetChildren().

0

workspace:GetChildren() creates a table of all instances that descend from workspace, and the loop you are using enumerates the items in the table with i, and assigns the item to b.

1 answer

✓ Accepted answer

Problem:

You can't do game.Workspace.b:Destory()

The reason being is that if you do it, the script will think you're trying to delete b, which in this case doesn't exist and will hence an error!

Solution:

If you want to delete "B" then make sure you use b.Name or something so that the script will not get confused.

If you want to delete everything in the workspace then type the following code:

wchildren = game.Workspace:GetChildren() -- Gets the children of the workspace
for a, b in ipairs(wchildren) do
    b:Destroy() -- destroys everthing in the workspace
print "The item has been destroyed!"
end

If this helped you, please accept!

2 comments

0

Yes, this works. I figured out that GetChlidren was making a table of userdata, not strings.

0

Fixed a minor grammatical error - January 31, 2021

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