Razc01na
Razc01na

Reputation: 13

What is this variable suposed to do on a lua generic for

I am new with lua. There is something I just can't understand about the so called generic for:

local L0 = {69, 145, 3, 70, 73, 30, 35}   
local L1, L2, L3 = nil, nil, nil

for L1, L2 in L0, L3 do  
print("Something") 

end

What is the purpose of L3 next to the table?

Upvotes: 1

Views: 115

Answers (1)

Piglet
Piglet

Reputation: 28950

Please refer to the Lua manual:

A generic for loop has the following syntax:

stat ::= for namelist in explist do block end
  namelist ::= Name {‘,’ Name}

The loop starts by evaluating explist to produce four values: an iterator function, a state, an initial value for the control variable, and a closing value.

So in your case

for L1, L2 in L0, L3 do  
  print("Something") 
end

L0 is supposed to be the iterator function and Lua tries to call it. As L0 is a table value, you face an error for trying to call a table value. And even if L0 were an iterator function you're still 2 values short. Actually as L3 is nil you're 3 values short. You see this code doesn't make much sense.

Most times generic for loops are used with ipairs or pairs which looks like

for k,v in pairs(sometable) do
 --block
end

or

for i,v in ipairs(someTable) do
-- block
end

I don't know where you found that code but I'd suggest you look for another resource for learning Lua.

http://www.lua.org is a good starting point. Both the manual and the free ebook verison of Programming in Lua are excellent resources.

Upvotes: 2

Related Questions