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

Help with functions

Started by Vesterpester, 21 November 2012 - 10:56 AM
Vesterpester #1
Posted 21 November 2012 - 11:56 AM
I feel shamed to do this, since Im basically asking you to make a script for me, but I have no earlier experience in coding.

Im building this thingy with 4 directional moving arm, which I would like to use with computer. The script would consist of only 4 repeating commands, each telling how to move to specific direction, like:

rs.setBundledOutput ("top", colors.red) –sends signal to motor
rs.setBundledOutput ("top", 0) –stops the signal
sleep(3) –waits for the arm to catch up

and then repeat it until the arm would have moved enough to one direction. Distances the arm moves are pretty big, so I really wouldt care for typing that scrip in there so many times. Ive undestood that with functions, I could do it somewhat like this:

function = ArmForward
rs.setBundledOutput ("top", colors.red)
rs.setBundledOutput ("top", 0)
sleep(3)
end

then my code would be like:

ArmForward
ArmForward
ArmForward
ArmLeft

etc…

Now, can somebody please explain how to do this in practically. I know, im a terrible person
dissy #2
Posted 21 November 2012 - 12:51 PM
You pretty much have the idea down. Functions basically let you group a bunch of commands under a name, to easily run the whole lot.
They have other features too of course, such as passing in data and getting data back.

In your case, I am assuming "red" of the bundled cable moves forward, and other colors move in other directions?

If that's the case, at the top of the script you can define the functions such as:

function ArmForward ()
  rs.setBundledOutput ("top", colors.red) --sends signal to motor
  rs.setBundledOutput ("top", 0) --stops the signal
  sleep(3) --waits for the arm to catch up
end

Copy/paste that and change the name (ArmForward, to ArmLeft) and in the new ArmLeft change the color as needed. Do that for each color/direction your machine can do.

Then you can either just call them like you just did, or use them in loops.
This would move the arm forward 3 times:

for c=1,3 do
  ArmForward()
end

(Edit: Corrected function call syntax in the for loop)
Vesterpester #3
Posted 21 November 2012 - 08:25 PM

function ArmForward ()
  rs.setBundledOutput ("top", colors.red) --sends signal to motor
  rs.setBundledOutput ("top", 0) --stops the signal
  sleep(3) --waits for the arm to catch up
end

Thank you really much! Learning the basics was easy, but those little extra marks have allways been hard for me.
remiX #4
Posted 21 November 2012 - 11:46 PM
This would move the arm forward 3 times:

for c=1,3 do
  ArmForward
end

You forgot the ()
dissy #5
Posted 22 November 2012 - 02:23 AM
This would move the arm forward 3 times:
 for c=1,3 do ArmForward end 
You forgot the ()

Ack, good catch, thank you! I will correct my above post for anyone referencing it in the future.