General > Developers Corner
Learning Lua... (Just a random post from a lua super noob.)
JamminR:
Close.
The if statement is inside the for loop, before the for loop finishes.
It would look like;
1 0
2 100
3 20
I found 20!
4 99
Now, a small lesson.
Placing that if statement outside the for loop would do nothing, wouldn't print anything.
For loops are 'local'. You can't use information/variables created within the actual 'for' statement unless you assign them to a variable outside the scope.
k would be nil outside. v would be nil. nil ~= 3, so nothing would be printed of the 'i found' line (and v would be nil too)
To make the code do the output like you originally said it would look like would be like this;
--- Code: ---x = { 0, 100, 20, 99 }
for k, v in ipairs( x ) do --k/v = local, x is a global (to this anyway) table
print ( k, v )
if k == 3 and v == 20 then c = 20 end --k/v = local, c = global
end
if c == 20 then print ( "I found " .. c .. "!") end
--- End code ---
(Oh, and though the 'and' comparison in the k= and v= is totally unnecessary (you could use 'if v == 20', I threw it in to show some logic operators.)
syn.:
Ohh okay thanks jam I mostly get confused on what is called what, for example I had no idea k and v were keys and values (even though in hindsight it seems a bit obvious).
Navigation
[0] Message Index
[*] Previous page
Go to full version