How to check if array is created using {} or :GetChildren()?

  1. What do you want to achieve?
    I want to be able to create a function that duplicates any kind of table/array to be referenced by a different variable.

  2. What is the issue?
    As written in the title, I don’t know how to check whether it is made by {} or :GetChildren(). I want to compare to use either ipairs or pairs.

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I have looked at the type of array that tables make, but specifically comparing these two, I can’t find a function for such.

local cloneTable

cloneTable = function(theTable)
	local newTable = {}
	
-- if from {} then
	for index, value in ipairs(theTable) do
		table.insert(newTable, value)
	end
	
-- if from :GetChildren() then
	for index, value in pairs(theTable) do
		table.insert(newTable, value)
	end
	
	return newTable
end

Using GetChildren(), you will most likely get a table of instances: parts, scripts, etc.

You would most likely use {} to store numbers or strings, I’m guessing.

You could do something like seeing if the Class is a part etc.

I can go for this approach, but your solution may require me to type down all the types of instances which is a hassle unless there is a way to check if the value is an Instance?

Check if it’s a value:

if not, use ‘else’

Why does the difference matter? ipairs is for arrays, which GetChildren returns so your example isn’t really ideal

Also are you aware of generalized iteration? A recent Luau update made it possible to iterate tables without an iterator function (pairs, ipairs, or next). You can think of it as a combination of all three; it is guaranteed to iterate arrays in order but unlike ipairs it will iterate the entire table regardless of the type of key used in each index

--this is now possible
for k, v in part:GetChildren() do

--so is this
for k, v in {1, 2, 3} do
1 Like

The thing is when I use an ipair for an array made by GetChildren(), I was only returned a portion of the table instead of all the values in GetChildren.

That really shouldn’t happen, GetChildren returns a proper array and ipairs should iterate through everything. Perhaps the problem is coming from somewhere else; I would check the rest of your script if I was you

I just realize it was the other way around when using pairs. I think I will go with ipairs from now on whenever I want to duplicate a table. And just to make sure I understand what you said before, I can pretty much use ipairs for any kind of table regardless of what I have asked in the title?

No. Generalized iteration is when you don’t use any built-in iterator function. ipairs will still act like ipairs where it only iterates the array portion of the table. It is different from GI.

1 Like