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

Can you pass boolean values as command line arguments?

Started by ChaosNicro, 17 April 2016 - 07:30 PM
ChaosNicro #1
Posted 17 April 2016 - 09:30 PM
Hello there,

I am trying to write a program that is supposed to take boolean type values as arguments.
When all the statements relating to these boolean values were considered true regardless of the input, I discovered that they had been picked up as strings instead.
I then solved this by using this construct:

if arg[2] == "false" then
   local direction = false
else
   local direction = true
end

I know it's considered a strength that Lua automatically assigns types to variables but is there a way to force a certain type?
Maybe I am better of using a different input and comparing to the strings.

Thanks in advance
Creator #2
Posted 17 April 2016 - 09:56 PM
Only strings.

Your solution does the job, so don't worry about it.
Lupus590 #3
Posted 17 April 2016 - 10:20 PM
a better solution would be


local direction --# otherwise this is local to the if statement
if arg[2] == "true" then
  direction = true
elseif arg[2] == "false" then
  direction = false
else
  --#insert some way to handle a bad argument
end
Edited on 17 April 2016 - 08:20 PM
MKlegoman357 #4
Posted 17 April 2016 - 10:46 PM
I know it's considered a strength that Lua automatically assigns types to variables…

It's the shell program that parses the arguments and gives you a string, not Lua. There's no such thing as 'automatically assign a type to a variable'. Just wanted to put away this misconception you might have had :)/>
Bomb Bloke #5
Posted 18 April 2016 - 12:01 AM
Well, there's no static typing, at least.

Anyway, another way of writing it:

local direction = arg[2]:lower() == "true"
ChaosNicro #6
Posted 18 April 2016 - 10:41 AM
Alright, thanks everyone.
That problem solved! ^_^/>
greygraphics #7
Posted 15 May 2016 - 05:37 PM
You could also use

local direction = (args[2] == "true" and true) or (false)
Lyqyd #8
Posted 15 May 2016 - 08:01 PM
That's redundant, though. Bomb Bloke's answer is simple and results in the same values being returned, but accepts all capitalization combinations of "true" as true.