Intercept event note played on phrase script

I can filter event notes in the script, but how do I determine the exact note that was played? The goal is to generate a scale based on the note played. Thanks for your suggestions.

You might want to use the trigger on the event context, this basic example will play C4 notes if C4 is the note that triggered the phrase, otherwise it won’t play anything.

return pattern {
  event = function(ctx)
    if ctx.trigger.notes[1].key == "C4" then
      return "C4"
    else
      return nil
    end
  end
}

Note, including some code you have been attempting (even if it doesn’t work) can help with understanding what you are trying to do!

Thanks for the reply; you understood what I need. I adapted your answer using the code I’ve attached, but it’s not working. Where am I going wrong?

return pattern {
  event = function(ctx)
    tonic = ctx.trigger.notes[1].key
    tonicmin = scale(string.sub(tonic, 1, 1), "minor")
    rand = math.randomstate(1234) -- a local random number generator
    return note(tonicmin.notes[rand(#tonicmin.notes)])    
  end
}

The issue is that you are creating the random generator with the same seed every time the function runs. The seed makes the generator deterministic, ie when you ask for random values with rand(), it will always return the same values in order.

Since you only generate a single random value from the same seed (and then discard the random generator), it will always be the same value.

Move the random generator into a generator scope:

return pattern {
  unit = "1/16",
  event = function(_) 
    -- now rand will only get created once and reused inside the event function
    -- giving you a different random value everytime you call it
    local rand = math.randomstate(1234)
    return function(ctx)
      local tonic = ctx.trigger.notes[1].key
      local tonicmin = scale(string.sub(tonic, 1, 1):lower(), "minor")
      return tonicmin.notes[math.floor(rand(#tonicmin.notes))]
    end
  end
}

see the doc page on generators for more explanation, alternatively you could have the rand in global scope.

As a rule of thumb it is also good practice to use local when declaring variables inside a function, this makes sure the function isn’t messing with global state.