i have a new project im working on, a datastore module.
since it’s supposed to be public, I want to specify what a function returns
it’s very simple to do this
function thing(): string
return "Hello"
end
print(thing())
but the problem is, I don’t know the type for tables.
i hope the solution isnt that simple
type test = {
var:string,
num:number,
pos:Vector3,
wtf:any,
}
function thing(): test
return {var="Test", num=1, pos=Vector3.zero, wtf={1, 5, 3, "Yes"}}
end
print(thing())
function thing2(): {var:string,num:number,pos:Vector3,wtf:any}
return {var="Test", num=1, pos=Vector3.zero, wtf={1, 5, 3, "Yes"}}
end
print(thing2())
To add tables to lua typechecking there is a multitude of methods
A simple one is
local function doSomething(t: {})
end
It doesn’t add much but the typechecker does count it as a table
For arrays you would just put the type inside the brackets. If any type can be in the brackets leave it empty or put any
local function doSomething(ArrayOfNumbers: {number})
print(ArrayOfNumbers[1]) -- should be a number
end
for dictionaries you use special indexing in typechecking
local function doSomething(dictOfStrings: {[string] : string})
print(dictOfStrings.hello) -- typechecker thinks is string
end
You can also add pre determined indexes
local function doSomething(playerData: {Money : number, Id : string})
print(playerData.Money) -- should be a number
print(playerData.Id) -- should be a string
end
You can also define typecheck objects with type
type objectThing = {
Name : string,
Age : number,
IsSomething : boolean
}
-- and add it to a table below like so
local function doSomething(object: objectThing)
print(object.Name) -- should be a string
print(object.IsSomething) -- should be a boolean
end
It can be confusing and seems like typechecking clutters up code. But for modules, especially public ones, it can be really useful since it gives it the same versatility as in game roblox services.
And no it does not decrease performance. All typechecking is removed/ignored in runtime and only works during scripting