Detecting if value is a model or string

I got a module, which creates a set of buttons. Each button will have either an ImageLabel or ViewportFrame. Basically, some items will be textures (for like wallpaper designs) and others will be models (like furniture)

What I am trying to do if detect whether said item is either a string (TextureId) or a model

CreateButton(item) -- item being a model
CreateButton(wallPaper.Texture) -- being the TextureId
1 Like
if type(x) ~= "string" and x:IsA("model") then
 -- Model Scope
elseif type(x) == "string" then
 -- String Scope
end

I kinda feel like if a string is passed though, its gonna error because strings don’t have an IsA method. So that might be something to look out for. Tried modifying it to account for this. but if you still get an error, just move the conditional after and inside of the model scope as an extra check.

9 Likes

if x is a number, then x:IsA("Model") (typo, btw) will error.

You can instead use typeof to check if it’s an instance.

if typeof(x) == "Instance" and x:IsA("Model") then
 -- Model Scope
elseif typeof(x) == "string" then
 -- String Scope
end
6 Likes

@T0ny’s solution is correct, assuming x will always be either a string or a type which implements IsA.
From lua.org:

Both and and or use short-cut evaluation, that is, they evaluate their second operand only when necessary.

So you could do

local a = "a string"
local test = ( type(a) == "string" or a:IsA("Model") )
print(test)

without any issues, because the evaluation stops after type(a) == "string", because no matter the result of the second part, the value of the full statement will be true. You’d only run into problems if you do

local a = 12
local test = ( type(a) == "string" or a:IsA("Model") )
print(test)

because the first part of the test evaluates to false, so it has to evaulate a:IsA("Model"), and IsA is not a method of number values.

2 Likes

I actually updated my code knowing the second operation wasn’t going to run. But I was only confident that it was true for an “or” statement. But wasn’t sure if “and” would behave the same. :slight_smile: So thanks for the clarification.

1 Like

Yes, that’s the case with the or operator. This is still not correct to use and you should not be relying on that short-cut evaluation. The second operand will error if IsA is not a valid member of the second operand. x is not always a string or type that incorporates IsA. Write your operands properly.

1 Like