Crystal-lang variable is defined

118 views
Skip to first unread message

Yılmaz DEMİR

unread,
Dec 7, 2017, 5:20:40 AM12/7/17
to Crystal

How can i check whether a variable is defined in Crystal?
For example, in PHP, like the isset function.

Kostya M

unread,
Dec 7, 2017, 9:09:03 AM12/7/17
to crysta...@googlegroups.com
you can use singleton for this: https://play.crystal-lang.org/#/r/37lf

2017-12-07 13:20 GMT+03:00 Yılmaz DEMİR <dem...@gmail.com>:

How can i check whether a variable is defined in Crystal?
For example, in PHP, like the isset function.

--
You received this message because you are subscribed to the Google Groups "Crystal" group.
To unsubscribe from this group and stop receiving emails from it, send an email to crystal-lang+unsubscribe@googlegroups.com.
To post to this group, send email to crysta...@googlegroups.com.
Visit this group at https://groups.google.com/group/crystal-lang.
To view this discussion on the web visit https://groups.google.com/d/msgid/crystal-lang/e73e17b2-e255-4266-9bff-5455bc928656%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Yılmaz DEMİR

unread,
Dec 7, 2017, 10:30:32 AM12/7/17
to Crystal
For local variables.

7 Aralık 2017 Perşembe 13:20:40 UTC+3 tarihinde Yılmaz DEMİR yazdı:

Luis Lavena

unread,
Dec 7, 2017, 10:59:17 AM12/7/17
to Crystal
Hello,


On Thursday, December 7, 2017 at 7:20:40 AM UTC-3, Yılmaz DEMİR wrote:

How can i check whether a variable is defined in Crystal?
For example, in PHP, like the isset function.

PHP is an interpreted language while Crystal is a compiled one.

AFAIK There is no way to check at runtime an undefined variable, simply because an attempt to use an undefined variable will produce an error during compilation:

Error in 9.cr:1: undefined local variable or method 'foo'

puts foo
     ^~~

This applies to branches, methods, anything that is invoked but is not defined.

You can only perform comparison against the value of variables and act based on that (ie. variable can be a number or nil)

In that case, you can use if to scope out other possible outcomes.

This behavior is documented in Crystal book:

https://crystal-lang.org/docs/syntax_and_semantics/if_var.html

Hope that helps.
--
Luis Lavena

Reply all
Reply to author
Forward
0 new messages