"t": A Runtime Type Checker for Roblox


#1

I made this for checking types during runtime. It’s designed specifically for Roblox, but also works in Lua5.1.

Give it a try, let me know if you have any questions or if the documentation could be more clear anywhere.


#2

Added error messages as a second return value from type checkers.

If you wrap your type check in an assert you’ll get the error message on failure:

assert(t.number("1")) --> number expected, got string

(these can get pretty complex based on your type definitions)

Different example:

local success, errMsg = t.number("1")
if success then
	-- do stuff
else
	warn(errMsg)
end

#3

Renamed the library to t. v was a bit too common…

Also improved testing! t is now rock solid.


#4

I would still prefer “tv”


#5

local tv = require(path.to.t)

:thinking:


#6

this is something ive always wanted to have but ive always been too lazy to make

very good 10/10


#7

How would you check that a number isn’t nan, +inf, or -inf?

(No reason, really. Just thought that someone may need to know this if the domain of a function is all real numbers. I’m using this library for my game <3)


#8

There isn’t a check built in for this, but you could totally make your own. (See tips and tricks in the readme)

I’ll consider adding something like this in the future.


#9

This… is just wonderful.


#10

Thanks, let me know if anything was confusing with the documentation.

Did you find any cool (or not obvious) uses for it?


#11

Not any particularly non-obvious uses, the documentation is good.


#12

Interestingly enough I made a runtime type checker a while ago.

The main difference is that I wanted to bind signatures to functions themselves, here’s an example.

local myFunction = validate("number", "string", function (a, b)
  print("Valid")
end)
myFunction(1, "Hi")
-- Valid
myFunction("Test")
-- Error: bad argument #1 to 'myFunction' (number expected, got string)

I realized that overrides were also quite important so added in support for them too.

myFunction:AddSignature("string")
myFunction("Test")
-- Valid

There is also support for varargs, so you can specify the type as ... and it’ll match any type.

local myOtherFunction = validate("function", "...", function (f, ...)
   f(...)
end)

#13

If there’s one thing I dislike about this library, it’s the name. Too short and makes it hard to search for (via Google, DevForum search)


#14

That’s definitely a downside to the name, but many people dislike having a different variable name from the library name. So a single letter encourages a short variable name. More complex type definitions require you to repeat the variable name often in the same line.