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.
maybe just
if getmetatable(x) then
print("Has Metatable")
end
Ozzypig
(Ozzypig)
#3
If you’re doing the idiomatic Lua OOP style like this,
local Car = {}
Car.__index = Car
function Car.new(color)
return setmetatable({
color = color;
speed = 0;
}, Car)
end
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`
end
Use the built in “getmetatable()” function.
7z99
(cody)
#5
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)
end
type coolObject = typeof(getType())
Then, typescript accepts this type to be used,
function object.new() : coolObject
local t = {}
return setmetatable(t, object) -- no errors
end
PS. I came across this site which has Roblox Typescript documentation.
2 Likes