I wish to become clearer with type checking. I understand what → does with functions, you can use it to control args and returns, but what does it do with tables if tables are data containers and don’t return anything (i think)?
I can’t find any simple explanations of this anywhere, it seems type checking is hard to explain and confusing.
I have tried figuring it out myself, but I barely understand the → thing and why it’s used.
{...} -> {...}
--btw before i had a custom function so i switched it with plain tables
aghhhh i hate type checking
The -> is just saying t: {} t is a table and it will return a table does that make sense?
Also, you should be using getmetatable() or setmetatable()
getmetatable(t: {...}) -> {...}?
setmetatable(t: {...}, mt: {...}?) -> {...}
The arrow → is used to specify what a function takes in, and what it outputs.
So in this line, it takes in a table, and returns a table.
It doesn’t change, whether its a table or not.
heres an example:
--!strict
local CarClass = {}
CarClass.__index = CarClass
export type Car = {
Brand : string,
Model : string,
returnCarInfo : (self : Car) -> {[string] : string}, -- () are where parameters go, {} is what the function returns
}
export type CarModule = {
new : (Brand : string, Model : string) -> Car,
}
function CarClass.new(Brand : string, Model : string) : Car
local self = setmetatable({}, CarClass) :: Car
self.Brand = Brand
self.Model = Model
return self
end
function CarClass.returnCarInfo(self : Car) : {[string] : string}
return {["Brand"] = self.Brand, ["Model"] = self.Model}
end
return CarClass :: CarModule
Let me know if you don’t understand something.
im also pretty sure metatable is not a method in the table library, it may only be if table is something custom.
oh yeah it was getmetatable that was a custom function i found in a module somewhere
how does a table return a table?
You mean this?:
local self = setmetatable({}, CarClass) -- :: Car
If your talking about that, its just defining a type like usual, something like this:
local a : number = 3
its just the scope doesn’t reach that part, so if you do 1 colon at the end, the autocomplete will think your doing something to the number, like a method, and not defining its type, the example on the top is the same as this:
local a = 3 :: number
I could have done this in the code I wrote, but I just have a habit of writing it like that, as the typechecker sometimes likes to cry and complain otherwise, you can also write it like this:
local self : Car = setmetatable({}, CarClass)
its the same.
OHHHHH OMG THAT SOLVES SO MANY OF MY PROBLEMS like when im setting variables i forget to set a type but now i can just add 2 at the end and problem solved