Can someone make a community tutorial on how to use autocomplete

Roblox Studio does it’s best autocompleting tables and stuff but sometimes it doesn’t know like in this example.

local PlayerProfiles = {}
PlayerProfiles.__index = PlayerProfiles

function PlayerProfiles.GetProfile(player)
	return PlayerProfiles[player]
end

function PlayerProfiles:AddBitcoin()
	
end


game.Players.PlayerAdded:Connect(function(player)
	PlayerProfiles[player] = setmetatable({}, PlayerProfiles)
end)

return PlayerProfiles

As you can see here there are no suggestions:
image

And here there are suggestions:
image

Even though they are the same object.

Is there a way to help guide the autocomplete by explicitly telling it the return type? I know you can do

function PlayerProfiles.GetProfile(player): {}
	return PlayerProfiles[player]
end

but all this says is that it returns a table and not which specific table.

Thanks for the help

I recommend having a look at this section of this tutorial to familiarize yourself with how to make types for tables: Type checking for beginners!

It doesn’t include how to use it with metatables but it’s still easy enough to do once you know the typeof type operator exists.

Anyway, you have 2 options really:

1- Define a type that has all the members of whatever your profile class would have, such as:

type profileProps = { -- whatever would appear in the profile's properties
	
}

type profileMethods = {
	GetProfile: (player: Player) -> profile;
	AddBitcoin: (self: profile) -> ();
	
	[Player]: profile;
	
	__index: profileMethods;
}

type profile = typeof(setmetatable({} :: profileProps, {} :: profileMethods))

then have GetProfile’s return type be profile, ie:

function PlayerProfiles.GetProfile(player): profile
	return PlayerProfiles[player]
end
PS

You can assert PlayerProfiles to be of type profileMethods to get self assigned a type in your profile methods

local PlayerProfiles = {} :: profileMethods

image

2- If you want profile to be an inferred type you need to make a function that creates a profile object instead.

local function makeProfile()
	local self = setmetatable({}, PlayerProfiles)
	
	return self
end

type profile = typeof(makeProfile())

Then you just make GetProfile’s return type to be profile, same as above

function PlayerProfiles.GetProfile(player): profile

In both cases you get your intended result:

1 Like

Thank You! This is exactly what I was looking for!

I always thought it was weird to do the first method you showed because then I would have to keep the profile type in sync with the profile object in order for it to be accurate. Almost like there were two sources of truth instead of one.

I never knew you could use typeof in this way

1 Like