Howdy, Stranger!

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

Pluralize widget

I'm using Sugarcube 2.12 to try to make a pluralize widget.

Use cases:
<<pluralize 2 "hour">> should return "2 hours"
<<pluralize 1 "item">> should return "1 item"
<<pluralize 3 "antenna" "e">> should return "3 antennae"

Here's what I've tried:
<<widget "pluralize">>
<<set _num = $args[0]>>
<<set _plu = $args[1]>>
<<if _num neq 1>>
  <<if $args[2]>>
    <<set _plu = _plu + $args[2]>>
  <<else>>
    <<set _plu = _plu + "s">>
  <</if>>
<</if>

<<= _num>>
<<= _plu>>
<<endwidget>>

However, weirdly, only the _plu is showing in all cases. The _num is never shown. At all.

But if I add
<<set _num += "">>
right before it's printed (on the blank line above), it's showing.

So I guess the widget is "working", (and now: Ryan Reynolds) but why?

Comments

  • You have a syntax error. You're missing one of the right angle brackets on your closing IF tag—i.e. you have <</if> rather than <</if>>. This is causing the closing IF tag to consume the print containing the _num temporary variable.

    You're also creating excessive numbers of line breaks. I'd suggest something like the following:
    <<widget "pluralize">>
    \<<silently>>
    	<<set _num = $args[0]>>
    	<<set _plu = $args[1]>>
    	<<if _num neq 1>>
    		<<if $args[2]>>
    			<<set _plu += $args[2]>>
    		<<else>>
    			<<set _plu += "s">>
    		<</if>>
    	<</if>>
    <</silently>>
    \_num _plu
    \<</widget>>
    


    Alternatively, if you're not using the _num temporary variable outside of the widget, then you could do the following instead—which does away with it:
    <<widget "pluralize">>
    \<<silently>>
    	<<set _plu = $args[0] + " " + $args[1]>>
    	<<if $args[0] neq 1>>
    		<<if $args[2]>>
    			<<set _plu += $args[2]>>
    		<<else>>
    			<<set _plu += "s">>
    		<</if>>
    	<</if>>
    <</silently>>
    \_plu
    \<</widget>>
    
  • I need to clean my glasses more, I guess.

    I'm using the nobr tag for my widgets-tagged Passage, it should be enough right? Should I add <<silently>> as well?
Sign In or Register to comment.