Storing services in _G

A more future proof solution would be this (converts dot notation into GetService calls, so you won’t need to update it):

-- use different names for some services
local Aliases = {
    Replicated = "ReplicatedStorage",
    Marketplace = "MarketplaceService",
    Collections = "CollectionService",
    -- and so on, append new aliases as necessary
}

-- get service with alias support
local function GetService(name)
    -- resolve aliases
    if Aliases[name] then
        name = Aliases[name]
    end
    return game:GetService(name)
end

-- return a table which implicitly calls GetService(name) whenever you index it
return setmetatable({}, {
    __index = function(_, service)
        return GetService(service) or error("Can't find service: " .. service)
    end
})

This solution will let you index all services without having to add each one to a table whenever you want to use it. You can also keep the alias support.

Just a small nice thing to have :stuck_out_tongue:

edit: for those of you who don’t care about aliases, you can cut down the code size considerably:

-- much smaller
return setmetatable({}, {
    __index = function(_, service)
        return game:GetService(service) or error("Can't find service: " .. service)
    end
})
7 Likes