|
| 18 Aug 2012 01:55 AM |
I know all the basics of scripting, and some advanced stuff. Something I've been really curious on how to work is the like "for i=1, #do"
or whatever lol. I've never understood that (the thing that singles things out in a way) |
|
|
| Report Abuse |
|
|
|
| 18 Aug 2012 01:56 AM |
Well
the #do is getting the length of the table.
..
|
|
|
| Report Abuse |
|
|
|
| 18 Aug 2012 02:14 AM |
things in [square brackets] describe what is put in that position, things in (brackets) are optional, the rest is necessary for the format.
for [variable name]=[starting number],[ending number] (,[step, default is 1]) do --code end
for example,
for numberz=2,10,2 do print(numberz) end
would count from 2 to 10 by 2s.
for omg=1,100 do print(omg) end
would count from 1 to 100 by 1 (the default number to count by) you can even count down:
for i=10,0,-1 do print(i) end print'Blast-off!'
would count from 10 down to 0 by -1 like a rocketship, because 0 is less than 10 and you cant count up from 10 to 0 by 1s.
#[variable name] represents the length of a table or string.
local tabel={1,2,3,4,5} local streng="7654321" print(#tabel)-->5 items in the table print(#streng)-->7 characters long for n=1,#tabel do print(tabel[n]) end for n=#streng,1,-1 do print(streng:sub(n,n)) end
>1 2 3 4 5 1 2 3 4 5 6 7
SCRIPTING 101 FTW |
|
|
| Report Abuse |
|
|
|
| 18 Aug 2012 02:24 AM |
local starting_value = 1 -- where it starts counting local ending_value = 10 -- where it stops counting local counting_increment = 2 -- how much it counts by
for index = starting_value, ending_value, counting_increment do print(index) end
>1 >3 >5 >7 >9
But you won't usually want to make it that complex. The most common use is for going through tables.
table = {"will", "the", "real", "slim", "shady", "please", "stand", "up"}
for index=1, #table do -- counting_increment is optional. If not given, it counts by 1 print(table[index]) -- this will print every indexed value in the table end
>will >the >real >slim >shady >please >stand >up
One of the most difficult concepts about the for structure is that it runs the inside code multiple times and the index is different each time. For example
table = {1,2,3,4}
runs = 0
function count() runs = runs + 1 end
for i=1, #table do count() -- the table has four indexed values, so this runs four times, so count is called four times, so runs is increased by one four times. end
print(runs)
>4 |
|
|
| Report Abuse |
|
|
|
| 18 Aug 2012 02:31 AM |
and about the fun one. pairs(table) returns next,table so I don't waste the billionth of a second required to call pairs().
local song={"will","the","real","slim","shady","please","stand","up"} for i,v in next,song do print(i,v) end
oyus. |
|
|
| Report Abuse |
|
|
|
| 18 Aug 2012 02:32 AM |
I forgot the output; >1 will 2 the 3 real 4 slim 5 shady 6 please 7 stand 8 up |
|
|
| Report Abuse |
|
|