So I have been coding my game stats for a while and I noticed that it’s impossible to have multiple base value’s so I have to check of what type they are here is an example
for Name, Val in pairs(PlayerData.Stats) do
if type(Val) == "number" then
local Value = Instance.new("NumberValue")
Value.Name = Name
Value.Value = Val
Value.Parent = Stats
elseif type(Val) == "string" then
local Value = Instance.new("StringValue")
Value.Name = Name
Value.Value = Val
Value.Parent = Stats
elseif type(Val) == "boolean" then
local Value = Instance.new("BoolValue")
Value.Name = Name
Value.Value = Val
Value.Parent = Stats
end
end
any solutions so just I can make the code smaller with no if statements?
local types = {
number = "Number",
string = "String",
boolean = "Bool"
}
for Name, Val in pairs(PlayerData.Stats) do
local ValueBase = Instance.new(types[typeof(Val)] .. "Value")
ValueBase.Name = Name
ValueBase.Value = Val
ValueBase.Parent = Stats
end
This just indexes the table with the different types. I also used typeof in place of type in case you want to support Roblox types (like Vector3) in the future.
also compound statements, although they’re only useful for small amount of statements
local type = typeof(x)
local className = (type == "string" and "String") or (type == "number" and "Number") or "Bool"
local value = Instance.new(("%sValue"):format(className))
...
An alterative idea to the two really good solutions above could be to use typed Lua instead and avoid this problem (Typescript follows a unique idea that variables are static and as such their type cannot change, thus meaning a number cannot become a string and vice versa. Its a good programming practice for many to not change their variable type.).