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

How do I check if an a variable is an objectValue?

Like for example, lets say I wanted to destroy my environment. I gather every variable and kill it.

for _, v in pairs(getfenv()) do
	v = nil
end

...but setting a variable to nil will only destroy an Object Reference

How could I check if v is a reference to an object in the game ahead of time so I can Destroy()it?

2 answers

You can use the IsA method, but treat it as a function:

if game.IsA( object, "Instance") then
	-- it's an Instance

There's a caveat, and that is that this will make an error if object isn't an instance. So you can use pcall:

local noError, wasInstance = pcall( function() return game.IsA(object, "Instance") end )
if noError and wasInstance then

You can preempt many of these pcalls by checking the type of the object is "userdata" (but this is not sufficient because Vector3, CFrame, etc are userdata, and also Lua scripts can make new userdata via newproxy):

if type(object) == "userdata" then
	local noError, wasInstance = pcall( function() return game.IsA(object, "Instance") end )
	if noError and wasInstance then
		-- it's a ROBLOX instance!
	end
end

2 comments

1

This is really stupid but can't you just check if it has .Name?

0

Other objects can have a name: local notAObject = {Name = "Hi"}. In a less strange example, BrickColors also have names.

Try this. Be careful though, we used this in Valkyrie and a Roblox update made it cause crashes for a bit before Roblox fixed their problem.

local function isInst(o)
if type(o) == 'userdata' then
local s,e == pcall(game.GetService, game, o);
return s and not e
end
return false
end
local env = getfenv()
for k,v in pairs(env) do
env[k] = nil;
if isInst(v) then v:Destroy() end
end

Remember that your env doesn't include things like game and Workspace, because they're in the env metatable index.

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