Should I delete ipairs?

Hello, I don’t quite know how to use pairs and ipairs and i don’t know if this edit is wrong because with it it doesn’t work anymore.
This is the original script

for _, NPC in ipairs(NPCFolder:GetChildren()) do

And this is my edit (“npc” is defined above)

for _, NPC in ipairs(npc) do

Any help is appreciated :slight_smile:

3 Likes

What are you even trying to do

3 Likes

I want to know how to replace this line, because if I use the second one the script doesn’t work

1 Like

Well the original script works just fine. Yours however, won’t. “npc” isn’t a table

1 Like

and how could I change it in a way that it works even with “npc”? Because I can’t use the other one

1 Like

Why couldn’t you? NPC is the current model the loop is at, NPCFolder is a folder, and the table or the folder’s children.

Listen, I have to readapt this script to my game, which I can’t adapt to the script. Do you know any way to fix this or not?

I don’t even understand your issue. ipairs is an iterator that runs through the provided table and returns an index and a value, in that order. What ??

NPCFolder doesn’t exist in my game, so i have to replace it with npc, which exists instead. My question is if there is any way to replace ipairs with something else because it clearely doesn’t work with “npc”

So instead of multiple NPCs in that folder, there’s just a single npc?

You haven’t showed us what “npc” is, like what type of data it points to. If npc is a table with an array part containing a list of NPCs, then ipairs will work. If it’s anything else (single NPC, table that’s a dictionary, string, etc.) it won’t. It’s as simple as that, ipairs iterates over the array part of a table, and GetChildren() always returns a table that has only an array part, no dictionary, which is why it’s used there. pairs will loop over all of the keys in a table, even if it’s a mix of array indices and dictionary keys.

yes, there is only one npc in workspace

local npc = game.Workspace.NPC

Then why can’t you just use this line? There’s no need for a loop now.

Well that still doesn’t tell me what NPC is, but it tells me it’s an Instance type that can be parented to the datamodel (Workspace), which means it’s not a Lua table. ipairs and pairs are for iterating over Lua tables.

Secondly, if it’s just one NPC, why do you need a loop?!

Just delete the whole for loop line, and corresponding end, and hard-code whatever is in the body of the loop to reference just npc instead of the loop variable NPC.

1 Like

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