ipairs

From Garry's Mod
Revision as of 17:10, 10 July 2016 by Zerf (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
 ipairs( )

Contents

Description

Returns an iterator function for a for loop, 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

table tab

The table to iterate over.

Returns

function

The iterator function.

Returns

table

The table being iterated over

Returns

number

The origin index =0

Examples

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

Examples

Example

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

local NUM = 32
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 > NUM ) then break end
end


Personal tools
Navigation