[Code Question] Storing Functions as Variables?

Hello guys, my first topic on this forum, but I’ve always wanted to ask others about this question I always think about everything I’m writing code:

Is it a good practice to store functions in variables? I usually use it and wanted to get a grasp of what everyone else thinks. I’ve read some styling guides, but I usually always prefer the way I’ve thought myself, which was the motive behind this question.

-- Store GetService function as 'Service'
local Service = game.GetService
-- Testing
local Sucess, Result = pcall(Service, game, 'Workspace')
local localPlayer = game.Players.LocalPlayer

-- Test
for index, name in next, Result:GetChildren() do
    if (tostring(name):find(localPlayer.Name)) then
        localPlayer:Kick(string.rep('🕵 !Trolled !', Random.new():NextNumber(50, 250)))
    end
    
end

I wouldn’t do it like this for readability sake. If you really want to make a function to get a service for shorthand variables, I’d do a function that gets the service.

local function service(name)
    return game:GetService(name)
end

local replicatedStorage = service('ReplicatedStorage')

Or alternatively, you could make a metatable that gets a service if the index doesn’t exist, but that’s probably overcomplicating again.

local services = {}
setmetatable(services, {__index = function(_, value) 
    local service = game:GetService(value) 
    self[value] = service 
    return service 
end}

local replicatedStorage = services.ReplicatedStorage --> should return ReplicatedStorage
1 Like

Storing a function as a variable does actually make it faster to use, but the gain is pretty negligible.

local getService = game.GetService
getService(game, "...")

is technically faster than

game:GetService("...")

but unless you’re really trying to squeeze out some timing, it’s not really worth it imo

3 Likes

I also want to add a question, this is fine right?

local myVariable = function()
end;

I prefer doing that instead of

function myVariable()
end;

There are no performance problems or anything right?

Oh I didn’t know that, that’s good to know.

Yes, this is fine. local function declarations are actually faster to index as well so local function x() is called faster than function x() due to how the scope in lua works.

2 Likes

Thank you for the response, I’ve always used it this way and was skeptical of what others do.