Jump to content




Using Arguments to Specify Iteration Quantities


  • You cannot reply to this topic
4 replies to this topic

#1 mike

  • New Members
  • 1 posts

Posted 22 July 2013 - 02:32 PM

ok, gotta say i like what ya did here....now i got a question for you. I want to repeat a program a wrote a certain number of times....however the number will change as I need it to. so would i have to individually edit the i=.() variable each time, or is there a way to input it when I run the program. (thinking along the lines of the tunnel program, asking how to long to dig the tunnel for)

#2 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 22 July 2013 - 09:14 PM

Split into new topic.

Read the sticky posts next time, please.

#3 Engineer

  • Members
  • 1,378 posts
  • LocationThe Netherlands

Posted 22 July 2013 - 10:21 PM

Simple enough!
local tArgs = { ... } --# Catch arguments from the command line
assert( tonumber( tArgs[1] ), "Number expected." ) --# error when it is not a number

for i = 1, tonumber( tArgs[1] ) do
 -- code
end


#4 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 22 July 2013 - 10:58 PM

Or to avoid tonumbering it twice

local args = {...}
local length = assert( tonumber(args[1]), "Number expected." ) --# store the return in a variable when there is no error

for i = 1, length do
  --# code
end


#5 KaoS

    Diabolical Coder

  • Members
  • 1,510 posts
  • LocationThat dark shadow under your bed...

Posted 23 July 2013 - 08:56 AM

why not just use the assert in the for loop?

EDIT: on an additional side note you do not have to turn args into a table either. randomFunc(...) will call randomFunc with all arguments passed to the program and you can pass multiple params to tonumber and it will use the first one.
All you need is
for nRun=1,assert(tonumber(...),"Number expected.") do
  --code
end

If you want to enter the number after running the prog use
write("Number of iterations: ") --could be tunnel length or anything
for nRun=1,assert(tonumber(read()),"Number expected.") do
  --code
end

Edited by KaoS, 23 July 2013 - 09:03 AM.






2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users