The difference and attention of ipairs and pairs in Lua

Source: Internet
Author: User

Basic class LBASELIB.C in Lua
this defines the underlying function, the function pointer array;
static const Lual_reg Base_funcs[] = {{  "assert", Luab_assert},  {"CollectGarbage", luab_collectgarbage},  {"Dofile", Luab_dofile},  {"Error", Luab_error},  {"Getmetatable", luab_getmetatable},  {"Ipairs", luab_ Ipairs},  {"LoadFile", Luab_loadfile},  {"Load", luab_load}, #if defined (lua_compat_loadstring)  {" LoadString ", luab_load}, #endif  {" Next ", Luab_next},  {" pairs ", luab_pairs},  {" Pcall ", Luab_pcall},  {"Print", Luab_print},  {"Rawequal", luab_rawequal},  {"Rawlen", Luab_rawlen}, {  "Rawget", Luab_rawget},  {"Rawset", luab_ Rawset},  {"Select", Luab_select},  {"Setmetatable", luab_setmetatable},  {"Tonumber", Luab_tonumber} {  "tostring", luab_tostring},  {"type", Luab_type}, {  "Xpcall", Luab_xpcall},  {null, null}};



Here are some common two uses, ipirs and pairs
1.pairs:
static int luab_pairs (Lua_state *l) {  return Pairsmeta (L, "__pairs", 0, Luab_next);}



lua.org Chinese Document This explains that if T has __pairs this meta method, it is called with table as a parameter, and the first 3 results are returned from the call, otherwise, 3 values are returned, namely: Next this method, the table, and a nil so this structure:
For k,v in pairs (t) do body end
all key-value in the table will be iterated

where next function:
static int Luab_next (Lua_state *l) {  Lual_checktype (L, 1, lua_ttable);  Lua_settop (L, 2);  /* Create a 2nd argument if there isn ' t one *  /if (Lua_next (L, 1))    return 2;  else {    lua_pushnil (L);    return 1;}  }



This function is also called to the main function of int luah_next (lua_state *l, Table *t, Stkid key). (The previous blog has introduced)

2.ipairs:
static int luab_ipairs (Lua_state *l) {  return Pairsmeta (L, "__ipairs", 1, Ipairsaux);}


lua.org Chinese Document This explains that if T has __pairs this meta method, it is called with table as a parameter, and the first 3 results are returned from the call, otherwise, 3 values are returned, respectively: iterator this method, the table, and a 0 so this structure:
For i,v in Ipairs (t) do body end
will iterate to (1,t[1]), (2,t[2]) .... Until the first integer key is not in the table.

corresponding function:
static int Ipairsaux (Lua_state *l) {  int i = Lual_checkint (L, 2);  Lual_checktype (L, 1, lua_ttable);  i++;  /* Next value *  /Lua_pushinteger (L, i);  Lua_rawgeti (L, 1, i);  Return (Lua_isnil (L,-1))? 1:2;}



and there's a key function in this function.
Const TValue *luah_getint (Table *t, int key)

For loop, pairs each time it gets the key, value, Ipairs is the index value and value,

a simple rough analysis of the two can be used and can not use the situation,

As An example ,
Local test = {1, 2, 3, 4}
for K, V in ipairs (test) do
print (k, v)
End

for I, V in pairs (test) do
print (i, v)
End

the output is all
1 1
2 2
3 3
4 4


Local test = {[1] = 1, [2] = 2, [3] = 3, [4] = 4}

for K, V in ipairs (test) do
print (k, v)
End

for I, V in pairs (test) do
print (i, v)
End

Output Result:
1 1
2 2
3 3
4 4
2 2
1 1
3 3
4 4
(which one is here to guide the next 12 why the reverse?) I guess it's the relationship of the main position they get through the hash algorithm .


Local test = {[1] = 1, [4] = 4}

for K, V in ipairs (test) do
print (k, v)
End

for I, V in pairs (test) do
print (i, v)
End

the output is:
1 1
1 1
4 4
if test is replaced by
Local test = {1, 2, [3] = 3, [4] = 4}
the output is all
1 1
2 2
3 3
4 4

change to local test = {[' a '] = 1, [' B '] = 2, [3] = 3, [4] = 4}
the output is
a 1
B 2
3 3
4 4

It is obvious that these two loops are affected by the two main functions listed above. Ipair can only traverse an array part of a table or the subscript is a hash table part of a number. And pair is all elements.

Local test = {[1] = 1, [2] = 2, [3] = nil, [4] = 4}
Local test = {[1] = 1, [2] = 2, [4] = 4}
this ipair will output
1 1
2 2
so Ipair to think of all the worthwhile elements, the subscript must be a sequential integer, and value cannot have nil, and pairs will not

so here in the actual operation of the time do not pay attention, a variety of length pairs ipairs disorderly use will appear strange problems.

like the table above.
Local test = {1, 2, 3, 4} If it is a store of other people's damage to the monster's buff, full 4, but this time the 3rd buff fails, then it is possible to write test[3] = nil and so on when the traversal if I Pairs or # Traversal, you will find the monster drop of blood will be very strange (with # taken to the length is 4), obviously has a length of 4, why only the first two blood loss of the value?

so to avoid such a simple but strange need to spend more time and energy to find mistakes. Suggested that, like the above situation, a value is not used, it is deleted with table.remove (note that the use of remove in the loop, remove the value, the following value will move forward one bit, resulting in the subsequent index values are out of the way, two solutions: one is to traverse the table from the back and forth, The other is when you traverse back to remove, minus the moved I, and do not use the value in the table as nil. and traverse when you can use pair traversal as far as possible with pair

The difference and attention of ipairs and pairs in Lua

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.