15 posts
Location
The Void
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
2679 posts
Location
You will never find me, muhahahahahaha
Posted 17 April 2016 - 09:56 PM
Only strings.
Your solution does the job, so don't worry about it.
2427 posts
Location
UK
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
1140 posts
Location
Kaunas, Lithuania
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 :)/>
7083 posts
Location
Tasmania (AU)
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"
15 posts
Location
The Void
Posted 18 April 2016 - 10:41 AM
Alright, thanks everyone.
That problem solved! ^_^/>
16 posts
Posted 15 May 2016 - 05:37 PM
You could also use
local direction = (args[2] == "true" and true) or (false)
8543 posts
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.