How to use type checking with metatables?

I need to add type checking to my tables that have metatables attached.

I can’t figure out how to define that a metatable is present.

I’ve tried looking for an @metatable, but that gave an error.

I’ve looked at a tutorial involving type checking, but found nothing relating to metatables.

Does anyone know the syntax, if it exists, to type check a table that has an attached metatable?

1 Like

I don’t know. :sweat_smile:
maybe just

if getmetatable(x) then
   print("Has Metatable")

If you’re doing the idiomatic Lua OOP style like this,

local Car = {}
Car.__index = Car

	return setmetatable({
		color = color;
		speed = 0;
	}, Car)

You could do something as simple as adding a self-reference within the Car metatable:

Car.Car = Car

Then to check that if some object is a specific type, you can do:

if object.Car == Car then
    -- It's a safe assumption that `object` has all the same members as `Car`

Use the built in “getmetatable()” function.

Essentially answered here but,

Roblox typescript has a built-in typeof function so I am pretty sure you’d do it like this:

local object = {}
object.__index = object
local function getType()
    return setmetatable({}, object)
type coolObject = typeof(getType())

Then, typescript accepts this type to be used,

function : coolObject
	local t = {}
	return setmetatable(t, object) -- no errors

PS. I came across this site which has Roblox Typescript documentation.