I know it's usually combined with a for i,v in pairs() do
loop (or ipairs
, or even next
) but what exactly is in
?
Just to clarify, I know how to use it, I just don't know the logic behind it, how does it work/what does it return?
Lua's in
is not a function or a variable. It's a part of the syntax for flow control. You can't replace it, you can't copy it, you can't even refer to it. It's rather like parentheses: a syntactic construct which has meaning for how a program is parsed, but which cannot be referred to within the program.
It doesn't "return" anything. It doesn't have "logic." It's more like a placeholder, or punctuation.
It doesn't do anything. It is syntax. It isn't a function. It isn't an opcode. It isn't a language feature. It is purely syntactical.
See the forlist
function in lparser.c
:
static void forlist (LexState *ls, TString *indexname) {
/* forlist -> NAME {,NAME} IN explist1 forbody */
FuncState *fs = ls->fs;
expdesc e;
int nvars = 0;
int line;
int base = fs->freereg;
/* create control variables */
new_localvarliteral(ls, "(for generator)", nvars++);
new_localvarliteral(ls, "(for state)", nvars++);
new_localvarliteral(ls, "(for control)", nvars++);
/* create declared variables */
new_localvar(ls, indexname, nvars++);
while (testnext(ls, ','))
new_localvar(ls, str_checkname(ls), nvars++);
checknext(ls, TK_IN);
line = ls->linenumber;
adjust_assign(ls, 3, explist1(ls, &e), &e);
luaK_checkstack(fs, 3); /* extra space to call generator */
forbody(ls, base, line, nvars - 3, 0);
}
Create the control variables.
Handle the local variables in the comma list.
Check that the next token is TK_IN
which maps to luaX_tokens
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With