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

How to initialize an argument?

Started by Ampix0, 14 May 2013 - 12:53 PM
Ampix0 #1
Posted 14 May 2013 - 02:53 PM
I am working on 1.5 of my SmartTurtleOS, and implementing the feature so you can tell the turtle how many blocks to move.


function smartMoveForward(distance)
for i=1,distance do
...

How do I set distance to "1" by default in case they enter "smartMoveForward()"
Lyqyd #2
Posted 14 May 2013 - 02:55 PM
distance = distance or 1
SadKingBilly #3
Posted 14 May 2013 - 02:55 PM
local distance = distance or 1

EDIT: :ph34r:/>'d

This works because when distance is nil (that is, when the user did not enter any value), it evaluates to false in an expression. Since it evaluates to false, Lua continues along the expression to 1 and assigns that to distance instead. If distance is not nil (that is, if the user did enter a value), it will evaluate to true, and Lua will ignore the remainder of the expression.
ikke009 #4
Posted 14 May 2013 - 02:55 PM
You can do something like
if not distance then distance = 1 end
that sets distance to 1 if distance is nil
maybe this would work too, although im not sure.. distance = distance or 1


Edit: double ninja'd :P/>