Quickest way to combine dictionaries

I want to combine two dictionaries whose keys are distinct strings. The easiest way I can think of is something like:

local a = {...} 
local b = {...} 

for i, v in pairs(a) do -- add a to b
    b[i] = v
end

I get the feeling that there must be something better because I’m continually expanding the size of b.

I am confused by what do you mean by that you are continually expanding the size of b if you are replacing values of table b with values of table a? Also, you should make a break with if statement in the script if I am correct here because you are going for i,v infinite loop and you are replacing nil value with nil value all the time. Also, I’d rather turn all values in b to nil first and then insert values from table a because there might be a value from table b still in table b from before.

This is definitely the best approach. If you’re worried about one of the tables being larger than the other, you can add b to a (the opposite) instead I guess, but this is really the only way to do it.

3 Likes

So is there no way to add multiple entries to a table at the same time?

You can do this with table.move

Yeah, I’m pretty sure. This is the best approach in vanilla Lua too, so unless Roblox has a custom function I don’t know about then this is the best. table.move is only for arrays as far as I know.

3 Likes

Doesn’t this only work for arrays?

2 Likes

I think it should still work, but I’m not sure - you could try and see.

@AstroCode
To add multiple entries to the dictionary yes , for example you would do something like :

simple for the sake of demonstration

local Dictionary = {
   [1] = {}
}

local folder = workspace:WaitForChild(“folder”)
      for i = 1 , #folder:GetChildren() do
          for _, child in ipairs (folder:GetChildren()) do
        Dictionary[i] = tostring(child.ClassName)
       for num,  class in pairs (Dictionary) do 
   print(num, class)

This would list all items’ classes in an array (folder’s children here) numerically in a dictionary . The output would be something like :

1 RemoteEvent
2 Part
3 Bindable Function

etc

I’m on mobile, please excuse the format

1 Like