How to create a new table inside a table

I’m trying to add every player’s magnitude between an NPC by adding a new table inside one that says the player name and it’s magnitude. Example:

local NPCCharacter = script.Parent --NPC Character

local PlayerDistance = {}
for i, Player in pairs(game.Players:GetChildren()) do
   local Distance = (Player.Charcter.HumanoidRootPart.Position - NPCCharacter.Position).Magnitude
   --inserts value and the player it used inside PlayerDistance
end

--How PlayerDistance should look like after for loop ended
PlayerDistance = {
   ["Player's Username1"] = {
      Username = --"Player's username"
      Distance = --Player's Distance
      },
   ["Player's Username2"] = {
      Username = --"Player's username"
      Distance = --Player's Distance
      },
   ["Player's Username3"] = {
      Username = --Player's username
      Distance = --Player's Distance
      } 
}
1 Like

Sorry! Had to quickly edit this because I realized I didnt write it the way I wanted it to

1 Like
local table1 = {}
table1["ArrayNameOrYourNewTableName"] = {}
1 Like

Want me to send the whole code?

1 Like

that would be nice! Please do.

1 Like

This should do the job:

local NPCCharacter = script.Parent

local PlayerDistance = {}
for i, Player in ipairs(game.Players:GetChildren()) do
	local DistancePos = (Player.Charcter.HumanoidRootPart.Position - NPCCharacter.Position).Magnitude
	PlayerDistance[Player.Name] = {
		Username = Player.Name,
		Distance = DistancePos
	}
end

wait change the pairs to ipairs sorry I didn’t tell you when I update it

1 Like

what’s the difference between pairs and ipairs? I’ve only seen it recently. If you dont want to say it’s fine

1 Like

ipairs is faster than pairs but the issues is that when using dictionaries with ipairs it won’t work.

2 Likes

These two screenshots would explain the difference between array and dictionaries


1 Like

Technically, Arrays and Dictionaries are the same. Arrays are { [number]: any } instead of { [string]: any }. For example, an array with three elements {1, 2, 3} is actually {[1] = 1, [2] = 2, [3] = 3}, it’s just the syntax.

2 Likes

yea I know :slight_smile: , I was just clarifying the other guy, so he won’t get confused

2 Likes

Wait can you answer the question about my confusion on what I am working on post?
There is still no answers sadly :sob: (The post is on my account)

1 Like

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