WoW:API ipairs: Difference between revisions

(Change category from "LUA Functions" to "Lua functions".)
m (Move page script moved page API ipairs to API ipairs without leaving a redirect)
 
(2 intermediate revisions by 2 users not shown)
Line 1: Line 1:
Native Lua statement:
{{luaapi}}
 
Returns an iterator triple that allows the Lua for loop to iterate over the array portion of a table.
Used in loop constructs to iterate through the values of a table where the index are only numbers, or where there is no index (an array).
iteratorFunc, table, startState = ipairs(table)
 
Example:


== Example ==
  local fruits={"apple","orange","banana","kiwi"}
  local fruits={"apple","orange","banana","kiwi"}


Line 20: Line 19:
would be output to the chat window.
would be output to the chat window.


{{LUA}}
Note that ipairs() starts at index 1 and stops counting as soon as it reaches a nil value. Example:
 
> t = { [0]      = "zero",  --will not be counted
        [1]      = "one",    --will be counted; 1
        [2]      = "two",    --will be counted; 2
        [3]      = "three",  --will be counted; 3
        ["four"] = "four",  --will not be counted; returns 3
        [5]      = "five" } --will never be reached
> for i,v in ipairs(t) do print(i..":"..v) end
1:one
2:two
3:three
 
Note that t[0] is never reached because it starts counting at [1], t["four"] is never reached because it is not an array index, and t[5] is never reached because the iterator ceases when it checks t[4] and finds a nil value.

Latest revision as of 04:46, 15 August 2023

WoW Lua

Returns an iterator triple that allows the Lua for loop to iterate over the array portion of a table.

iteratorFunc, table, startState = ipairs(table)

Example

local fruits={"apple","orange","banana","kiwi"}
for index,value in ipairs(fruits) do 
  DEFAULT_CHAT_FRAME:AddMessage(tostring(index).." : "..value)
end

Result:

 1 : apple
 2 : orange
 3 : banana
 4 : kiwi

would be output to the chat window.

Note that ipairs() starts at index 1 and stops counting as soon as it reaches a nil value. Example:

> t = { [0]      = "zero",   --will not be counted
        [1]      = "one",    --will be counted; 1
        [2]      = "two",    --will be counted; 2
        [3]      = "three",  --will be counted; 3
        ["four"] = "four",   --will not be counted; returns 3
        [5]      = "five" }  --will never be reached
> for i,v in ipairs(t) do print(i..":"..v) end
1:one
2:two
3:three

Note that t[0] is never reached because it starts counting at [1], t["four"] is never reached because it is not an array index, and t[5] is never reached because the iterator ceases when it checks t[4] and finds a nil value.