I would really like to know, right now all I can understand is the index
function. Would someone mind explaining the rest?
Take a look at this:
pairs
, ipairs
and next
are the built-in global functions used in generic for loops for indexing through tables. I don't know anything about an "index" function.
local t={'a','b','c','d','e','f',a=1,b=2,c=4,d=8,e=16,f=32} for _,v in pairs(t)do print(_,v) end
Output:
1 a 2 b 3 c 4 d 5 e 6 f d 8 e 16 f 32 a 1 b 2 c 4
pairs has no particular order for indices that are non-numerical.
for _,v in ipairs(t)do print(_,v) end
Output:
1 a 2 b 3 c 4 d 5 e 6 f
ipairs does not index non-numerical indices at all.
for _,v in next,t do print(_,v) end
Output:
(same output as pairs)
Calling next(t)
will tell you whether or not the table is empty.
The generic for loop can also be used with your own functions:
for v in function(_,n) return(n or 0)+1 end do print(v) end
This will count up forever.
While true do -- Infinite Loop, crashes if there is no wait() print("hi") wait(1) end
for i = 1,10 do --For loop. This loop will print yo 10 times. print("yo") end