NotAshley
|
  |
| Joined: 16 Jan 2014 |
| Total Posts: 14257 |
|
|
| 20 Jul 2015 04:15 AM |
What does each individual operator do in this line, in order to create the magic that is a for loop?
for i, v in next, tbl do
Mainly "for," "in," and "next." We all know what they do bunched together, but are they wired into Lua only for that purpose, or are they logic operators that could theoretically be used on their own? |
|
|
| Report Abuse |
|
|
| |
|
NotAshley
|
  |
| Joined: 16 Jan 2014 |
| Total Posts: 14257 |
|
|
| 20 Jul 2015 04:20 AM |
| @masterblokz are you 100% sure? I think that's a bit of a narrow minded way to think of it. I wanna fully understand everything I run. |
|
|
| Report Abuse |
|
|
| |
|
ShungTzu
|
  |
| Joined: 14 Jun 2014 |
| Total Posts: 959 |
|
|
| 20 Jul 2015 04:39 AM |
I wouldn't mind seeing a more thorough explanation of these, myself. For now, see what you can glean from these.
http://www.lua.org/pil/7.3.html http://www.lua.org/pil/4.3.5.html http://www.lua.org/pil/4.3.4.html
|
|
|
| Report Abuse |
|
|
cntkillme
|
  |
| Joined: 07 Apr 2008 |
| Total Posts: 44956 |
|
|
| 20 Jul 2015 05:32 AM |
for ... in ... do is the generic for loop.
What a generic for loop does is uses an iterator function and calls it over and over until it returns nil. So here:
for i,v in next, tbl do for i,v in pars(tbl) do
The first one is calling the next function, with the first argument being the tbl The second one is calling the pairs function, which returns next, with first arg being tbl So those two work exactly the same (except for a tiny function call at the start).
But you're not limited to "next", "pairs", or "ipairs".
local word = function(str, idx) idx = idx or str:find("%S+"); local phrase, count = str:sub(idx):match("(%S+)(%s*)"); if phrase then idx = idx + #phrase + #count; return idx, phrase; end end;
for nextWordPos, phrase in word, "hello there friends!" do print(nextWordPos, phrase); end
Here, it'll print: 7 hello 13 there 21 friends |
|
|
| Report Abuse |
|
|
cntkillme
|
  |
| Joined: 07 Apr 2008 |
| Total Posts: 44956 |
|
|
| 20 Jul 2015 05:38 AM |
21 friends!*
Also you've probably used string.gmatch within a generic for loop. Maybe even io.lines? The point is, "next" is simply just another function that was implemented to go over a table using the previous key.
x = {a = 5, b = 10, 15, 20};
local i, v = next(x); -- nil second argument print(i, v); -- might be a 5 or b 10 or 1 15 or 2 20 print(next(x, i)); -- it will be different from the above one, using the last key it gets the next pair. |
|
|
| Report Abuse |
|
|
NotAshley
|
  |
| Joined: 16 Jan 2014 |
| Total Posts: 14257 |
|
|
| 20 Jul 2015 05:38 AM |
| @cnt awesome! thanks for the explanation. I knew there was more to it. |
|
|
| Report Abuse |
|
|