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

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

Asked by 9 years ago

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

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

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
1
This is really stupid but can't you just check if it has .Name? randomsmileyface 375 — 9y
0
Other objects can have a name: `local notAObject = {Name = "Hi"}`. In a less strange example, BrickColors also have names. BlueTaslem 18071 — 9y
Ad
Log in to vote
0
Answered by 9 years ago

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.

Answer this question