Should i use _G?

hello. i am wondering whether or not i should use _G to hold a function being used very commonly like tween(). is it better to have a tween function in every script that uses it, have a tween function in _G and have scripts access it, connect scripts to a modulescript with tween() in it, or should i just use tweenservice:create()?

1 Like

For what you’re describing, I’d never used _G or shared.

Instead, a ModuleScript is what you’re looking for:

In a ModuleScript:

local module = {}

function module.tween(part: Part)
    -- some code
end

return module

In a Script:

local RS: ReplicatedStorage = game:GetService("ReplicatedStorage")
local functions: ModuleScript = require(RS:WaitForChild("ModuleScript"))
functions.tween(game.Workspace.Part)
2 Likes

what are some of the main problems that _G has?

by the way, tween() will have to be used across 50+ scripts. could it cause memory problems if the modulescript is accessed by many scripts?

It depends on your use-case.

_G or shared are a table that can be accessed across different scripts. If you were to assign all your functions to them, then you sacrifice readability (at least for me: I tend to organise code thematically around a task). Similarly, variables assigned to them remain in memory and aren’t collected, so you’re running into a lot of memory being used.

Not at all! A ModuleScript is more efficient in your scenario, albeit CPU-intensive.

1 Like

i have a few small scripts here and there that just detect clicks on a textbutton. is it better to just use tweensrevice:create() in that scenario?

The way I’d approach this is to iterate over all the parts you’re tweening:

local TS: TweenService = game:GetService("TweenService")

function tween()
    for k, v in pairs(game.Workspace.Parts:GetChildren()) do
        local t: Tween = TS:Create(v, TweenInfo.new(1), {Transparency = 1})
        t:Play()
        t.Completed:Wait()
    end
end

text_button.Activated:Connect(tween)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.