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
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.