Jump to content




Can you pass boolean values as command line arguments?


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

#1 ChaosNicro

  • Members
  • 15 posts
  • LocationThe Void

Posted 17 April 2016 - 08: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

#2 Creator

    Mad Dash Victor

  • Members
  • 2,168 posts
  • LocationYou will never find me, muhahahahahaha

Posted 17 April 2016 - 08:56 PM

Only strings.

Your solution does the job, so don't worry about it.

#3 Lupus590

  • Members
  • 2,028 posts
  • LocationUK

Posted 17 April 2016 - 09: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 by Lupus590, 17 April 2016 - 09:20 PM.


#4 MKlegoman357

  • Members
  • 1,170 posts
  • LocationKaunas, Lithuania

Posted 17 April 2016 - 09:46 PM

View PostChaosNicro, on 17 April 2016 - 08:30 PM, said:

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 :)

#5 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 17 April 2016 - 11:01 PM

Well, there's no static typing, at least.

Anyway, another way of writing it:

local direction = arg[2]:lower() == "true"


#6 ChaosNicro

  • Members
  • 15 posts
  • LocationThe Void

Posted 18 April 2016 - 09:41 AM

Alright, thanks everyone.
That problem solved! ^_^

#7 greygraphics

  • Members
  • 16 posts

Posted 15 May 2016 - 04:37 PM

You could also use
local direction = (args[2] == "true" and true) or (false)


#8 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 15 May 2016 - 07: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.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users