Garry's Mod Wiki

ents.Iterator

  function, table, number ents.Iterator()

Description

Returns a Stateless Iterator for all entities. Intended for use in Generic For Loops.
See player.Iterator for a similar function for all players.

Internally, this function uses cached values that exist entirely within lua, as opposed to ents.GetAll, which is a C++ function. Because switching from lua to C++ (and vice versa) incurs a performance cost, this function will be somewhat more efficient than ents.GetAll.

The GM:OnEntityCreated and GM:EntityRemoved hooks are used internally to invalidate this function's cache. Using this function inside those hooks is not guaranteed to use an up-to-date cache because hooks are currently executed in an arbitrary order.
An error being thrown inside the GM:OnEntityCreated or GM:EntityRemoved hooks is likely to break this function. Make it certain that no addons are causing any errors in those hooks.

Returns

1 function
The Iterator Function from ipairs
2 table
Table of all existing Entities. This is a cached copy of ents.GetAll
This table is intended to be read-only.

Modifying the return table will affect all subsequent calls to this function until the cache is refreshed, replacing all of your ents.GetAll usages may come with unintended side effects because of this.

3 number
The starting index for the table of players.
This is always 0 and is returned for the benefit of Generic For Loops

Example

Example usage of this function.

for _, ent in ents.Iterator() do if ( ent:GetClass() == "prop_physics" ) then ent:Remove() end end
Output: All physics props will be deleted.