Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sugarcube 2: how to evaluate a condition stored as a string in a variable

In sugarcube 2 (twine 2), how can I evaluate a condition stored as a string in a variable.
Example:
<<set $condition = "$var1 gt 1 or $var2 gt 1">>
<<if $condition>> /* it should be evaluated as <<if $var1 gt 1 or $var2 gt 1>> and NOT as if $condition is blank or not*/
<<print "condition is true, i.e. $var1 is greater than 1 or $var2 is greater than 1"
<</if>>

Essentially, the condition to be used is dynamic, and hence I want to store & set it in a variable instead of hard coding it.

How can this be done?

Thanks in advance for your time and inputs.

Comments

  • Can someone confirm whether this can be done or not. Thanks
  • Please do not bump threads when it's barely been a day since you asked your question.


    If you can get away with it, you'd be better off simply storing the result of the condition. For example:
    /* If you can evaluate the condition in one go. */
    <<set $condition to $var1 gt 1 or $var2 gt 1>>
    
    
    /* If you have to assemble the condition in stages. */
    <<set $condition to $var1 gt 1>>
    …
    <<set $condition to $condition or $var2 gt 1>>
    
    At that point, $condition will be set to the boolean result of the logical expression and you'd simply check that value as normal. For example:
    <<if $condition>> …
    

    If you cannot do that due to temporal reasons—i.e. the values of the variables will change between point where you setup the condition and the <<if>> where you need to check it—then you may evaluate your TwineScript code string like so:
    <<if Scripting.evalTwineScript($conditional)>> …
    
    n.b. If you do this and need to use strings as part of your conditional, pay attention to your quotes.
  • thanks a lot. sorry for bumping. i did not realize my query would result into that, i just had a deadline and became desperate for an answer. will keep this mind going forward.
Sign In or Register to comment.