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

Convert A Nil Value To A String

Started by Roboguy99, 16 November 2013 - 09:30 AM
Roboguy99 #1
Posted 16 November 2013 - 10:30 AM
The title basically explains what I want to do. How would I go about getting a variable, seeing if it is a nil value and then convert it into a string (make it say "none")?

Here is my current code:


if currentMissile == nil then
currentMissile = None
end

currentMissile is created from an ICBM missile launcher through the command launcher.currentMissile() and returns nil if there is nothing. I would like it to say none.
Lyqyd #2
Posted 16 November 2013 - 02:48 PM
Put quotes around None, so you are setting it to: "None"
Imred Gemu #3
Posted 16 November 2013 - 10:09 PM

if currentMissile == nil then
currentMissile = "None"
end
or

if currentMissile == nil then
currentMissile = 'None'
end
theoriginalbit #4
Posted 17 November 2013 - 03:52 AM
It should also be pointed out that the use of and and or here can be quite useful.

In Lua variables resolve differently in conditionals than in most other languages, false and nil when present in a conditional will both resolve to false, any other value will resolve to true. Making use of this knowledge will allow you to do the following


currentMissile = currentMissile or "None"

the above code basically says that if currentMissile is false or nil, it will now become "None".

Do take note however this method does not work for boolean variables as if you did the following


someBoolean = someBoolean or true

it would not be a guaranteed boolean, since any value does resolve to true, obviously as such you can do

someBoolean = someBoolean == true
which says "is someBoolean true?" so if true is supplied, it will remain true, anything else, it will become false.

We can also extend this functionality to say remove statements like the following

if [some condition] then
  someVar = 1
else
  someVar = 3
end

by using the closest thing to a Ternary statement that Lua has to offer

someVar = [some condition] and 1 or 3
which follows the format of

[conditional] and [value-if-true] or [value-if-false]
the only time that this will fail is in the event that the value-if-true is false or nil, which will always result in the value-if-false being used.
Roboguy99 #5
Posted 20 November 2013 - 07:52 AM
Thanks guys. Should have put the speech marks (stupid mistake) and ended up using 'or' as my solution.

[color=#000000][size=2]currentMissile [/size][/color][color=#666600][size=2]=[/size][/color][color=#000000][size=2] currentMissile [/size][/color][color=#000088][size=2]or[/size][/color][color=#000000][size=2] [/size][/color][color=#008800][size=2]"None"