This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
mike's profile picture

Using Arguments to Specify Iteration Quantities

Started by mike, 22 July 2013 - 01:32 PM
mike #1
Posted 22 July 2013 - 03: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)
Lyqyd #2
Posted 22 July 2013 - 10:14 PM
Split into new topic.

Read the sticky posts next time, please.
Engineer #3
Posted 22 July 2013 - 11: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
theoriginalbit #4
Posted 22 July 2013 - 11: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
KaoS #5
Posted 23 July 2013 - 09: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 on 23 July 2013 - 08:03 AM