|
| 01 Mar 2015 03:55 PM |
| actually mean or do? I just go off of them by memory and use them as needed, but I wanna go more in-depth. |
|
|
| Report Abuse |
|
chimmihc
|
  |
| Joined: 01 Sep 2014 |
| Total Posts: 17143 |
|
|
| 01 Mar 2015 03:57 PM |
pairs gets all the things in the table
ipairs gets array values(any that you dont set an index for) |
|
|
| Report Abuse |
|
|
| 01 Mar 2015 04:00 PM |
pairs is an iterator function. Behind the scenes, generic Lua for loops call pairs for each iteration, and the function returns your I and v variables or another value, if we've iterated over the whole table.
ipairs is basically the same, but only works on keys that are integers.
next is a keyword. They do things, don't ask questions :) I don't know what next does, but I guess it's special syntax for the for loop to iterate over a table.
The generic for loop doesn't need to actually use those things. You can make your own iterator function, and there is a string manip function that can be used as an iterator:
for v in string.gmatch(str, "[^\n]+") do
This will loop over every line in a string. |
|
|
| Report Abuse |
|
cntkillme
|
  |
| Joined: 07 Apr 2008 |
| Total Posts: 44956 |
|
|
| 01 Mar 2015 04:12 PM |
Pairs calls next, so just think of pairs as a wrapper of next, since it technically.
Let's start with the easy part: ipairs
I'm sure you've used a numerical loop before, think of ipairs as using a counter (because it is). It will count from 1 up to #table, if there is a "hole" (aka a nil) then the loop will actually stop. So it's kind of like: for key = 1, #tbl do if tbl[key] == nil then return; end end
Except that it's an iterator function, so in reality it's more like this: local ipairs = function(tbl) local key = 0; return function() key = key + 1; if not tbl[key] or key >= #tbl then return; else return key, tbl[key], "hello"; --i, v, this last part is just to show you that you can essentially do whatever you really want with iterators, real ipairs doesn't have this end end; end;
for i, v, x in ipairs({1, 2, 3}) do print(i, v, x); end -- 1 1 hello -- 2 2 hello
Ipairs is guaranteed to go in order, but over only the array part of the table (1, 2, 3, ..., #n) such that (tbl[i] ~= nil) This also means it can not find anything "out of order"/in the hash part of the table (tbl["a"] = 5 or tbl[0] = 3 or tbl[2] = 5 where tbl[1] was not defined)
Pairs calls next, which goes over both the hash part AND the array part. Pairs works basically like this: local pairs = function(tbl) return next, tbl, nil; end; |
|
|
| Report Abuse |
|