for-loops in gen~ to fill a table
Hi to everyone, I'm working on some GenExpr and during this work some questions about efficiency arose, and in particular about the for-loop usage.
As far as I Know, gen~ calculations are executed for every incoming sample so if, for example, I'd like to fill a table using a for-loop, is this loop executed for every incoming audio sample?
In this case wouldn't be more efficient to fill the table using Max/MSP objects and compute the fill-up only once?
Is there a way to execute the gen~ code only once?
Thanks in advance
Matteo
Yes, the trick is to just run the for loop once, not on every sample, which you can do by wrapping it in an appropriate if() condition.
If you only want to do it once, when a patch loads, wrap it in a
if (elapsed == 1) {
// for loop goes here
}
(This is because "elapsed" is an operator/variable in gen~ that tells you how many samples have passed since the patcher loaded.)
If you want to do it whenever a certain trigger signal happens, wrap it in:
if (change(trigger > 0) > 0) {
// for loop goes here
}
The trigger could be a param, or a signal input. Whenever it rises above zero, it will trigger for just one sample (so the for loop runs once) and won't do it again until the trigger has gone back to zero (or below) first. That should work for most use cases.
If you want to allow both, just join them with an or operation:
if (elapsed == 1 || change(trigger > 0) > 0) {
// for loop goes here
}
HTH!