• Remove NPC:s from table
    4 replies, posted
[lua] local npcs = ents.FindByClass("npc_*") for i=1,table.Count(npcs) do if(npcs[i]!=nil and npcs[i]:IsValid() and npcs[i]:GetClass() == "npc_testx") then table.remove(npcs, i) end end [/lua] Doesn't work. All I want to do is to remove all "npc_testx" from a table. How I do it?
[lua]local npcs = ents.FindByClass("npc_*") for i,v in ipairs(npcs) d if(v~=nil) then if v:IsValid() and v == "npc_testx" then table.remove(npcs, i) end end end[/lua] Does this work? Also a point of interest, you don't need to use table.Count at all. You can just use a hash. e.g. [lua] food={"cake","pie","fish"} print(#food) print(table.Count(food)) //Same results! [/lua] It looks as if you were using "!=" when you should have been using "~=". Brackets are also not required for "if" in lua. Remember, check if it's nil FIRST, because IsValid is a function of the entity, and you can't call it on nil as nil has no functions.
Not all NPCs necessarily have the "npc_" prefix in their classname, so if you want to make sure to get all NPCs aside from the ones with the "npc_testx" classname, do this instead: [LUA]local tbNPCs = {} for _, ent in ipairs(ents.GetAll()) do if(ent:IsNPC() && ent:GetClass() != "npc_testx") then table.insert(tbNPCs,ent) end end[/LUA] [QUOTE=Ylsid;32058213] It looks as if you were using "!=" when you should have been using "~=".[/QUOTE] Both are valid syntaxes in glua.
[QUOTE=Silverlan;32089100]Not all NPCs necessarily have the "npc_" prefix in their classname, so if you want to make sure to get all NPCs aside from the ones with the "npc_testx" classname, do this instead: [LUA]local tbNPCs = {} for _, ent in ipairs(ents.GetAll()) do if(ent:IsNPC() && ent:GetClass() != "npc_testx") then table.insert(tbNPCs,ent) end end[/LUA] Both are valid syntaxes in glua.[/QUOTE] Really? I wonder why garry'd do that. I was right about the rest though, yes? I don't want to be giving out false information ;)
[QUOTE=Silverlan;32089100] [LUA]local tbNPCs = {} for _, ent in ipairs(ents.GetAll()) do if(ent:IsNPC() && ent:GetClass() != "npc_testx") then table.insert(tbNPCs,ent) end end[/LUA] [/QUOTE] I don't recomend doing this as it is very expensive. You could do it once at startup in case of any NPCs loaded by the map, but other than that try to avoid looping over ents.GetAll() Set up a table that indexes NPCs each time they get created. Look at the table later to get all NPCs
Sorry, you need to Log In to post a reply to this thread.