"Attempt to call a nil value" when everything seems to be defined

So I’m trying to loop through a table, and it’s giving me an error where it tries to loop through. Here’s the code.

local Steps = {
	game.Workspace["Step1"],
	game.Workspace["Step2"],
	game.Workspace["Step3"]
}

for _, part in pairs(Steps:GetChildren()) do

It’s failing on the last line, and I don’t understand why

You’re assuming that the GetChildren() function is a valid property/member of a table object, but it isn’t

What you can instead do, is first reference the table, then reference every Step you want to find using the GetChildren()

local Steps = {
	game.Workspace["Step1"],
	game.Workspace["Step2"],
	game.Workspace["Step3"]
}

for _, Step in pairs(Steps) do
    for _, Part in pairs(Step:GetChildren()) do
        --Now do your stuff here
    end
end

This is what would be known as a “nested loop”, or a loop inside of another loop

3 Likes

I don’t understand why it isn’t. I’m fine with this fix, but can you explain this?

you could also use a regular for loop for looping though tables

local Steps = {
	game.Workspace["Step1"],
	game.Workspace["Step2"],
	game.Workspace["Step3"]
}

for i = 1, #Steps, 1 do
    Steps[i]
end

Because table is not an instance and you never defined a function named GetChildren in the table or hooked up a metatable that has a __index metamethod in it that can call a function named GetChildren that’s why.

Tables are general-coded in programming, sure they may have functions (table.insert, table.remove), but you can’t reference them the same way as you can with Instances

GetChildren() is not a valid member of a table, is basically what it is since those only work with Instance values

1 Like