The Crystal Programming Language Forum

Seems to be crashing by doing math?

I’m trying to run a script, but when I use += to increment a variable by any value it crashes. Stating “undefined method + for Nil (compile-time type is String | Nil)” which I don’t really understand too much, but I haven’t been able to work around it. If anyone could help, it would be great

The issue here is that one of the variables you are trying to add has Nil as one of its possible types.

if rand(2) > 0
  val = 1
end

puts 1 + val

In this example, it fails to compile with the error no overload matches 'Int32#+' with type (Int32 | Nil).

This prevents the possible issue of nil can't be coerced into Integer that you would get in Ruby if the random value made the if block falsy.

Make sure that both of your values are not nilable. Such as

  
if rand(2) > 0
  val = 1
end


if v = val
  puts 1 + v
end

It also seems the type of your variable is String | Nil. Make sure to convert your string to a number for the math to actually work, and not just concat the two values.

If you can create a playground link from https://play.crystal-lang.org/#/cr I could take a look and give a working example.

1 Like

https://play.crystal-lang.org/#/r/7510
Hope that link works, and would be great if you can get it functioning
Not sure how to convert something to a number, but that probably is the issue

Whoa, I was expecting something much simpler :stuck_out_tongue:

Basically what’s going on is when you first define your stats, they are of type Int32. But their type gets overridden to String | Nil when you prompt the user for their stats, since data coming from console is going to be a string. The Nil comes into play because there is some case where that attribute would be nil, which would obs error when trying to add something to it.

I managed to get it working by doing .not_nil!.to_i after all of your gets that edit the values of your stats. However that isn’t a real good solution (unless you are 100% sure they will never be nil), nor does it handle invalid number input. (https://play.crystal-lang.org/#/r/751k)

Another tip that would help is if you defined type restrictions on your methods. def weaken(str : Int32, dex : Int32, agi : Int32, cla : Int32, fld : Int32, log : Int32) This would cause a compile time error if you tried to pass a value to the method, that is of not an allowed type.

I’m not sure if this makes it more clear or not. So here is some reference material:

definitely helped, got it running again. Still not doing the math, but it’s not crashing at least. So it’s still an improvement. Thanks

Note that it wasn’t “crashing”, you just got a compiler message, your code didn’t run at all