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?
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 pcall
s 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
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.