Howdy, Stranger!

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

[Twine 2.1.1][SugarCube 2.14] Passing anonymous function to a widget/macro directly

Hey there,

This is more of a cosmetic questions, but still important to me. I'm trying to pass an anonymous function to a widget that would use that function to filter items in an inventory for me. Here's how the call looks like:

This doesn't work:
 <<listItemsFiltered $player function(item){return item.type === 'top'}>>

This works, but I'm passing a function that was assigned.
<<set $showTopsOnly to function(item){return item.type === 'top'}>>
<<listItemsFiltered $player $showTopsOnly>>

Any ideas of what I'm doing wrong here?


  • As noted in the macro library documentation—at the top:
    Macros fall into two broad categories based on the kind of arguments they accept: those that want an expression (e.g. <<set>> and <<print>>) and those that want discrete arguments separated by whitespace (e.g. <<link>> and <<audio>>). The documentation for each macro will tell you what it expects.


    Passing the result of an expression as an argument is problematic for a couple of reasons: because the macro argument parser doesn't treat arguments as expressions by default and because it separates arguments with whitespace.

    Normally, those aren't issues as you should not need to use the result of an expression as an argument terribly often. To resolve instances where you do, however, you'll want to use either a temporary variable or a backtick expression.

    You should be doing one of three things with your predicate function here:
    1. If it's going to be reused, setting it up as a static method of setup. For example: (Twine 2: Story JavaScript; Twine 1: script-tagged passage)
      setup.isTop = function (item) {
      	return item.type === 'top';
      <<listItemsFiltered $player setup.isTop>>
      This works because setup, along with settings, receives special attention during argument processing.
    2. If it's a one-off, assigning it to a temporary variable. For example:
      <<set _isTop to function (item) { return item.type === 'top'; }>>\
      <<listItemsFiltered $player _isTop>>
    3. If it's a one-off, using a backtick expression . For example:
      <<listItemsFiltered $player `function (item) { return item.type === 'top'; }`>>
  • Thank you! That answers my question!
Sign In or Register to comment.