so i saw a youtube tutorial that uses getservice for rep storage and players, i use game.rep… and game.players. i was wondering if theres any pros and cons to each of them?
for example:
vid:
Are essentially the same thing but if you use the first code and for whatever reason the name of your “Players” service is not “Players” but something else it will not be an error.
GetService is a function provided by Roblox that takes in a string and returns a service.
Doing it “your way”, that is using the . operator to reference a child of game, is directly accessing the child by its name (with the exception of Workspace, which is also a property of game)
While they both work, and points and counterpoints could be made to argue for either method (i.e. . may be shorter, Roblox wouldn’t realistically remove service names, etc.), the Roblox Lua style guide recommends this:
All services should be referenced using game:GetService at the top of the file.
Since Workspace, Players, ReplicatedStorage, etc. are all considered “Services”, GetService is the preferred method for getting a reference to them. This creates consistency across all your code.
There are some other more hypothetical benefits:
Roblox may change the name of a service and deprecate or remove an old name. In such cases, Roblox can update the GetService function to return the new service, whereas the . operator to access the child of the game would error.
If your code somehow runs before a service is initialized, calling GetService will ensure that the service exists (source: ServiceProvider.GetService docs), whereas the . operator would error
It’s possible to rename services, and in such cases, getting it via GetService will still work, but attempting to access them via . operator would error