Luau runtime typechecking?

Is there any way to check if variables have luau types? (Using a modulescript or a luau language feature)
You’d be able to do this:

type test = {
  a: number
}

local test2 = {a = 1}
local test3 = 2

print(luautypeof(test2, test)) --true
print(luautypeof(test3, test)) --false


EDIT: Is there also any way to check what type of object an instance is?
(Part, GuiObject, Decal, ect.)
The answer to this question above is Instance.ClassName

1 Like

You cannot check for custom Luau types. The closest you can get to that is doing something like this:

local oldtypeof = typeof
local function typeof(object): string
   if oldtypeof(object) == "table" then
      local mt = getmetatable(object)
      return if mt then mt.__type else "table"
   end
   return oldtypeof(object)
end

local object = setmetatable({}, {__type="customobject"})
print(typeof(object)) --> "customobject"

But that’s not well-crafted for a lot of different situations


Either Instance.ClassName or Instance:IsA() (if you want to check for class inheritance)

2 Likes

That will not work, as i’m actually checking if a variable received from a remote event is the custom luau type to prevent errors caused by exploits from the client side

shopBuyEvent.OnServerEvent:Connect(function(player: Player, buyingType: string, basket: {[string]: number})

how do I validate that basket is the type assumed?

You can use a runtime typechecking module. The best one I know of is t, written by osyrisrblx (Roblox employee). It follows quite similar principles to Luau’s static typing.

1 Like

So, you’re saying runtime luau typechecking isn’t possible?

Not that I know of. Luau is statically typed. I’ve seen some effective uses of t though, and some popular open source networking libraries use either t or their own version. Iirc Red uses a custom one called Guard.

For marking types on objects HugeCoolboy2007’s approach is pretty nice. Unfortunately metatables are lost on their way across the network.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.