Creating multiple instances at once

I’m trying to create a script that creates instances based off number and tables. It works but any improvements I should do?

local nums = {
	[1] = {
		["Name"] = "leaderstats",
		["Instance"] = "Folder"
	},
	[2] = {
		["Name"] = "lol",
		["Instance"] = "NumberValue"
	}
}
local parents = {
	[1] = function(Player)
		return Player
	end,
	[2] = function(Player)
		return Player.leaderstats
	end
}
game:GetService("Players").PlayerAdded:Connect(function(Player)
	for i=1, 2 do
		local D = Instance.new(nums[i].Instance)
		D.Name = nums[i].Name
		D.Parent = parents[i](Player)
	end
end)

I think something with a table called “children” would be better, I’ll write a quick code to make more sense.

Here

local players = game:GetService("Players")

type InstanceTable = {
	name: string,
	instance: string,
	children: {InstanceTable?}?,
	getParent: ((player: Player?) -> (Player|Instance)?)?
}

local instances: {InstanceTable} = {
	{
		name = "leaderstats",
		instance = "Folder",
		getParent = function(player)
			return player
		end,
		children = {
			{
				name = "lol",
				instance = "NumberValue"
			}
		}
	},
}

local function createInstance(data: InstanceTable, player: Player?): Instance
	local parent: Instance = Instance.new(data.instance)
	parent.Name = data.name
	parent.Parent = data.getParent and data.getParent(player) or nil
	
	for i, v in pairs(data.children or {}) do
		local child = createInstance(v)
		child.Parent = parent
	end
	
	return parent
end

players.PlayerAdded:Connect(function(player)
	for i, v in pairs(instances) do
		createInstance(v, player)
	end
end)

If it doesn’t make sense feel free to ask any questions you want.

You could use more descriptive function and variable names, and you can use a loop instead of hard-coding the number of children/elements in nums and parents; you can use the # operator to get the length of a table!

Also you could rewrite those first 2 variables like this:

local stats = {
	{
		name = "leaderstats",
		instance = "Folder"
	},
	{
		name = "lol",
		instance = "NumberValue"
	}
}

local parents = {
	function(player)
		return player
	end,
	function(player)
		return player.leaderstats
	end
}

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