If/Else Conditional Not Working with a Defined v. Undefined Variable

New to Twine, fairly new to programming, but have some grasp on some basics.

Using the latest Twine ver. as of this post and Sugarcube 2 (currnet ver. as of end 2022).

Running into an issue with a conditional which looks like it should be working to me, but something is going awry!

In the previous passage “name” is either defined or undefined by the player.
They can continue to the next passage w/out entering their name.

What I want to happen is that if they’ve entered their name and clicked to go to the next passage it should show “Welcome ‘name’.” - this part is working.

What’s not working is that if they do not enter their name and continue to the next passage instead of reading “Welcome they who have not been named.” it’s returning “Welcome .”

(There is text before this and I wanted to use the time effect for some additional, well, effects.)

Going into test mode “else” is crossed out.

<<timed 1s>>Welcome <<if $name is not undefined>>$name.
<<else>>they who have not been named.
1 Like

I tested this with just the code you provided and it works - it displays “Welcome they who have not been named”.

Are you defining $name somewhere else in your story? For example, if you set it to an empty string (<<set $name to "">>) in your StoryInit, it will not be undefined, and the game will display just “Welcome .”

You can also change <<if $name is not undefined>> to just <<if $name>>, which I believe is shorthand for “if the variable is defined and not empty” (can’t find the reference to that now, but when I test this version, it displays “Welcome they who have not been named” when $name has been set to an empty string).

1 Like

To check if a variable is defined, you can use

<<if $var>> <- check if truthy (defined, > 0, or true)
<<if def $var>>
<<if $var is ... >> <- to check if it is a specific value

and vice-versa for undefined

<<if !$var>>  <- check if falsy (undefined, 0, or false)
<<if ndef $var>>
<<if $var isnot ...>>
1 Like

Thanks! I didn’t think I had it defined, but it looks like this was the problem and I didn’t realize the text box would still work without the second set of double quotes:

Before you enter, tell us your name: <<textbox "$name" "">>

Removed them and it’s working now :slight_smile:

1 Like

Somewhat spoke too soon as I was quick testing and without the empty quotes, the textbox did not work.
However, to solve I changed the if statement to ’ if $name is not “” ’ which seems to have worked!