Garry's Mod Wiki

ipairs

  function, table, number ipairs( table tab )

Description

Returns a Stateless Iterator for a Generic For Loops, to return ordered key-value pairs from a table.

This will only iterate though numerical keys, and these must also be sequential; starting at 1 with no gaps.

For unordered pairs, see pairs.

For pairs sorted by key in alphabetical order, see SortedPairs.

Arguments

1 table tab
The table to iterate over.

Returns

1 function
The iterator function.
2 table
The table being iterated over.
3 number
The origin index =0.

Example

Demonstrates how this differs from pairs.

local tbl = { two = 2, one = 1, "alpha", "bravo", [3] = "charlie", [5] = "echo", [6] = "foxtrot" } print( "pairs:" ) for k, v in pairs( tbl ) do print( k, v ) end print( "\nipairs:" ) for k, v in ipairs( tbl ) do print( k, v ) end
Output:
pairs: 1 alpha 2 bravo 3 charlie 5 echo 6 foxtrot one 1 two 2 ipairs: 1 alpha 2 bravo 3 charlie

Example

From UpdateUI in undo.lua, this adds the first 100 undo entries to the Undo panel in the spawnmenu.

local Limit = 100 local Count = 0 for k, v in ipairs( ClientUndos ) do local Item = ComboBox:AddItem( tostring( v.Name ) ) Item.DoClick = function() RunConsoleCommand( "gmod_undonum", tostring( v.Key ) ) end Count = Count + 1 if ( Count > Limit ) then break end end