Hello! I am starting to use Luau for type checking, and I’m doing good since I have experience with TypeScript (Luau equivalent for JavaScript) and I have a question:
What type(s) are used to define an Instance in Luau?
Here’s a situation: you’re doing a function that changes a part’s position, and has 2 parameters: the part to be modifed and the position. This is how the code would look:
local function changePartPos(part: ???,pos: Vector3)
part.Position = pos
end
What would be the type for the part parameter?? I already trying putting Instance but it says Instance doesn’t have a key named Position:
Thanks in advance!!
If it helps, visualize the class (type) hierarchy as a tree. This is called inheritance. Many Instances in Roblox extend from an abstract Instance. In the case of Parts, BasePart is the root of the tree, and Part, TrussPart, MeshPart, etc. are the branches - they branch off from the root. If a class doesn’t have anything extending from it, it is called a leaf(Instance (root) -> BasePart (branch) -> TrussPart (leaf). Abstract means the type cannot be created/instantiated. For example, this code is invalid: Instance.new("BasePart")
You cannot create a BasePart, but you can create one of the BaseParttypes that extend from the abstract BasePart class.
Here’s where it gets weird: Everything is an Instance. Even BasePart. So, now we have an even deeper root. Another abstract type is GUIObject. If we implement that into our visual hierarchy, our tree now may look something like this:
[Instance]
|
___________________________________________________.. --> A LOT of other Instance classes, some abstract, some not! -->
| |
[BasePart] [GUIObject]
| |
____________________________ __________________________.. --> A LOT of other GUIObject classes -->
| | | | | |
[Part] [TrussPart] [MeshPart] [Frame] [TextLabel] [Image]
The particular issue with your code is exactly as you described: You need to provide an Instance that has a Position property. You can supply a type “Part”, but this will create an issue later down the line if you or someone else tries to pass in a “TrussPart” to your function - your code will cry and you will be sad. To get around this, use the root class: BasePart, which every other part extends from! You’re covering all the bases, woohoo!
Thanks, I always thought the only class that could be used to define other ones(abstract) was BasePart, also, found a link for anyone browsing this topic with all the classes and their “parents” and “childs”: https://roblox.fandom.com/wiki/Class_reference