What is the typeof() function in Roblox and what is it useful for?
To kick off, typeof()
is a very special function made by Roblox which returns a specified datatype as a string.
print(typeof(1)) -- Prints out datatype number
print(typeof("")) -- Prints out datatype string
print(typeof(false)) -- Prints out datatype boolean
Already this is useful for:
- Preventing exploiters from sending different datatypes to break your scripts or send multiple error messages in the output
- Helping scripts check a returned datatype and then run certain code afterwards
- Adding an extra layer of security to your game
Examples that use the typeof()
function
I will now show you some useful examples that use the typeof()
function and explain how it each example works along the way.
This useful example uses the typeof()
function to check what datatype a variable is holding.
local MyValue = 10
if typeof(MyValue) ~= "number" then -- Checks if the variable is a holding a number or not
print("Invalid datatype!")
else
print("Valid datatype!")
end
This useful example uses the typeof()
function to check what datatype is being returned from the client.
RemoteEvent:FireServer("Hello World!") -- Client sends this string to the server
RemoteEvent.OnServerEvent:Connect(function(Player, Value) -- The server receives the RemoteEvent sent by the client and the value sent across as well
if typeof(Value) ~= "string" then -- Checks if the value sent by the client is a string or not
print("Invalid datatype!")
else
print("Valid datatype!")
end
end)
Why do we use the typeof()
function instead of the type()
function?
You may have already noticed that there is also another function called type()
which sort of works the same as the typeof()
function. Except, the only difference is the typeof()
function is a Roblox Global whereas the type()
function is an Lua Global.
In conclusion, it is recommended that developers use the typeof()
function on Roblox instead of the type()
function.
If you would like to read up more on the typeof()
function and the type()
function, here are the documentation pages: Roblox Globals | Roblox Creator Documentation, Lua Globals | Roblox Creator Documentation
I hope this helps.