Every programmer have to go through basics, but in Roblox, one thing that is very basic is seen as unimportant or strange, this… those things are types
Many begineers never learn about them (or at least not in a direct way), which is a big mistake, why?
Advantages of using types
- They allows others to easily change your code, for instance, settings
- They makes your code more redable for you and your co-scripters
- They allow you to check if variable belongs to specific type or not
- You can create your own custom types
How to use types
Soo, it’s pretty straightforward
local a: number = 5 --/ we add semicolon after variable and we choose from types list
local b: boolean = true
local c: string = "Hello"
We can also use types in tables
local OurList: {string} = {"Lemon", "Orange", "Apple"}
And at the end, we can also use values as types
local b: true = true
local c: "Hello string" = "Hello"
Note: You can’t use numbers here!
Type checking
Soo, apart of setting type to help read our code, we can also check if something belongs to specific type
local a = 5 --/ i didn't added type because it's optional, value still holds number type
if typeof(a) == "number" then
print("a is a number")
else
print("a isn't a number")
end
Note: You can’t use type checks with custom types!
Custom types
To create your own custom type, you need to export it, here is how we do it:
export type TableWithEverything = {any} --/ After = symbol we write roblox types or variable types
local OurList: TableWithEverything = {5, 4, true, "Hello", "Lemon", 10}
As you can see, when we press semicolon the code assist suggest TableWithEverything as valid type
Note: We can set our variable’s type to custom one without exporting it, although it’s better and more visually appealing to export it soo it will be highlighted and more understood by others
Additional tips
- We can use & or | to create multitype
local BooleanOrNumber: number | boolean
or
export type StringAndTable = string & {}
-
You shouldn’t use types in middle of scripts, only in function arguments or while working on values that can change (settings variables are the best examples)
-
You should consider removing comments that explain what value should be like, instead use types
example:
local GunClass = {} --/ OOP class
GunClass.__index = GunClass
vs
local Gun: Class = {}
Gun__index = Gun
Overall, i believe you understood what types are and you will use them in your scripts to improve them
i wish you a nice day, and bye!