Is there a way to optimize this defaults system?

Hello, I have a system in my code where if a certain parameter is not passed, it will default to the value specified in the script, I was desperate to get this working so I kinda clumsily put it together. I want it to be more optimized and potentially less prone to failure. I haven’t tried optimizing it because I have no idea how I’d go about this as I’m a fairly rookie programmer. Thank you for all your help!

PS: Please note that this code may be called at many places, all at once.

local Args = ...
local Defaults = {Duration = -1, DisplayReason = "No Reason Was Provided!", PrivateReason = "No Reason Was Provided!", ExcludeAltAccounts = true, ApplyToUniverse = true}
local Config = {UserIds = UserIds,Duration = nil,DisplayReason = nil,PrivateReason = nil,ExcludeAltAccounts = nil,ApplyToUniverse = nil}
		
		for i, v in pairs(Defaults) do
			if Args[i] ~= nil then
				Config[i] = Args[i]
			else
				Config[i] = Defaults[i]
			end
		end

PPS: I had plans for removing the Config table and just using the Defaults table instead, but would this work? Would this table be reset for every use of the ModuleScript, or would it carry over?

Not sure if you know this, but you can use ‘or’ incase there is no parameter specified.

Example :

local function print(message)
   message = message or "Hello world!"
   print(message)
end

-- Output is either going to be the message, otherwise it will default to "Hello world!"
2 Likes

You can use metatables, they can handle defaults really well!

The __Index will run when you try to access a NIL value, which then you can substitute for a default value! This is really helpful and I would recommend using this as it’s more professional.

-- This is the default data that we will get our default data from.
local defaultData = {
    ["Cash"] = 250,
    ["Gems"] = 50
}

-- This is the metamethod that handles when you try to access a nil value.
-- When using setmetatable(), it basically applies this table to the input table.
local meta = {
    __index = function(data,value)
        data[value] = defaultData[value]
        return defaultData[value]
    end,
}

-- This would be your Config here, that is passed.
local data = {
    ["Cash"] = 975,
}

-- Give the Config/Data the meta, which basically connects the function to it.
setmetatable(data,meta)

print(data.Gems) -- Will print out 50, 
print(data.Cash) -- Will print out 975, since we already had it defined.
-- Gems is 50 since our data didn't have it. Cash is still 975.
2 Likes

Oooh this looks interesting, I’ll have to look into this sometime, thanks!

1 Like