File SMUtils.mys

SMCore main file with many utility functions, also includes main SMCore files with essential classes.

Including SMUtils also include most part of SMCore library:

as well as MSDefine.

Author
Sylvain Machefert

Class

ClassSummary
StopwatchStopwatch (French: chronomètre) to measure elapsed time.

Sections

SectionSummary
AccessibilityAccessibility functions, mostly audio messages.
AssertionsAssertion functions, that extend Lua assert(...) standard function.
BarsBars utility functions.
BatchBatch processing.
BooleanAlgebraBoolean algebra functions.
ChordsChord class and other chords utility functions, like extracting chords from the chord line of a staff.
ClefsClefs utility functions.
ColorsColor utility functions.
CurvesParameter curves utility functions.
DebugDebugg and log functions.
DevToolsSome dev tools for script authors
DiagramsChord diagrams utility functions
DrumsDrums grids, play and other utility function.
DurationsClock and durations utility functions
  • Clock: measure elapsed time, time formating,
  • Conversions from/to milliseconds, note duration, percentage of note duration, 256th of quarter
DynamicsDynamics utility functions
FXProcessorsFXProcessor handling utility functions.
FilesFiles utility functions
FontsFont utility functions.
FreeObjectsFreeObject utility functions.
GraphicsUtility functions for images, drawing on Graph
InputsInput functions, to ask user to enter number, select in a list of choices, two values as XY coordinates.
InstrumentsHarmony's Instruments utility functions
InternetInternet functions.
IntervalsInterval constants
KeySignaturesKeySignature utility functions.
MIDIMIDI utility functions.
Numbersnumbers utility functions.
OrnamentsOrnaments utility functions
PicturesStaff picture utility functions
PlayPlay utility functions: play the score, play a sound...
PreferencesPreferences functions: workaround for bogus or missing function that read global preferences.
ReflectionMyrScript reflection Reflective programming or reflection is the ability of a script to examine, introspect, and modify its own structure.
RulesRules utility functions
ScoresScore utility functions
StaffTextsStaffText utility functions
StavesStaff utility functions
StavesGroupsStavesGroup utility functions
StorageAreasStorageArea utility function
Stringsstrings utility functions
SymbolsSymbols (notes, rests...) utility functions
SyntaxExtend Lua language: assertions, logging, switch/case, bit operations...
Tablestables utility functions.
TargetsTarget utility functions.
TempoTempo utility functions
UnicodeUnicode representation of some musical symbols, and Unicode string functions.
ViewsView utility functions

Summary

ConstantTypeSummary
BAR_STATE_AFTER_PRINT_REGIONintBar state visibility: not visible, after last printed bar
BAR_STATE_BEFORE_PRINT_REGIONintBar state visibility: not visible, before first printed bar
BAR_STATE_MULTI_FIRSTintBar visibility state: visible, first bar of a multi-rest or multi-repeat.
BAR_STATE_MULTI_LASTintBar visibility state: not visible, last bar of a multi-rest or multi-repeat.
BAR_STATE_MULTI_MIDDLEintBar visibility state: not visible, inside (but not last bar of) a multi-rest or multi-repeat.
BAR_STATE_UNDEFINEDintBar visibility state: undefined: should not happen.
BAR_STATE_VISIBLEintBar visibility state: normal, visible.
Return typeFunction and summary
booleanAND(boolean ...)
AND function in boolean algebra, that accepts undefined number of arguments.
 AddImagesDirectory(string path)
Add a directory where script can search for pictures.
intAdjustStavesGroupSymbolPosition(Score score, table groups)
Experimental: Adjust horizontal and vertical staves group symbole (braces and brackets).
 ArrayClear(table t)
Optimization of clearing a table.
booleanArrayContains(table tab, term)
Does tab contains term?
 BatchAdd(string batchName, string label, function func)
Stack a function for batch processing.
 BatchClear(string batchName)
Clear the batch stack, in case of cancellation or when all calls are done.
intBatchExecute(string batchName, Score score, object)
Execute the batch function stack on the objects in argument table.
 BatchIsRecording(string batchName)
Is the batch currently stacking?
 BatchStartRecording(string batchName)
Just set a flag that tells we are currently recording and stacking functions for further batch processing.
 BatchStopRecording(string batchName)
Cancel the flag that tells we are recording and stacking operations for batch processing, without clearing the stack.
intBinNot(int a, int bits)
NOT bitwise operation MyrScript comes with BinAnd(...), BinOr(...), BinXor(...), BinShl(...), BinShr(...) but not the NOT bitwise operation.
string, string, intChooseColor(string object, table suggestedColors, selected)
Ask the user to choose one color in a menu.
string, int, int, stringChooseFont(string object, table suggestedFonts, selected)
Ask the user to choose one font in a menu.
intChooseNoteHeadShape(int defaultValue)
Open a dialog to choose a note head shape.
tableChooseStaves(Score score, boolean multiple, boolean visibleOnly, function filterFunc, function selectFunc, int minNbOfChoice, int maxNbOfChoice)
Ask the user to choose one or multiple staves.
tableChooseStavesGroups(Score score, boolean multiple, boolean visibleOnly, function filterFunc, function selectFunc)
Ask the user to choose one or multiple staves groups.
TargetChooseTarget(Score score, string prompt, int selectedBar, string selectedName)
Select a Target (rehearsal mark) in the Score.
intChooseView(Score score, boolean index, int (default=current)
Ask the user to choose one view, or a value for ViewIndex.
stringCompareMyrScriptVersion(string version)
Is MyrScript =, < or > version x.y.z?
intCompareSymbolsByPitch(Symbol a, Symbol b)
Compare two Symbols by pitch, then displayed height.
table, int, int, intCompareTables(table lines1, table lines2)
Compare two tables, returns a diff-like format.
stringCompareVersions(string a, string b)
Compare two version numbers in x.y.z string format.
 CopyBarNumberings(Staff source, Staff dest)
Copy bar numberings settings from one staff to another.
 CopyFXProcessor(FXProcessor source, FXProcessor dest)
Copy all parameters from a FXProcessor to another one.
intCopyFreeObjects(Score src, Score dest)
Copy free objects from one Score to another.
int, intCopyOrnaments(Symbol from, Symbol to)
Copy all ornaments from a Symbol to another one.
intDeleteAllFreeObjects(Score score)
Delete all free objects from a score, without confirmation.
intDeleteAllTargets(Score score, boolean preserveScore)
Delete all targets (rehearsal marks) from a score.
intDeleteDisabledCurves(Staff staff)
Remove the parameter curves that have been disabled.
intDeleteEmptyCurves(Staff staff)
Remove the empty parameter curves when they have no values.
intDeleteHiddenFreeObjects(Score score)
Delete all hidden free objects from a score, without confirmation.
 DeleteReservedPages(Score score)
Delete reserved pages from a score, if any, and move or delete the free objects visible on the reserved pages.
intDeleteUselessClefs(Staff staff)
Delete useless clef change that are visible clefs with no changes.
 Deserialize(string str)
Deserialize a string into object.
intDontSplitTwoAndFourRepeats(Score score, int firstBar, int lastBar)
In current view, avoid split (end of line) in the middle of %2 and %4 bar-repeats.
booleanDynamicIsOttava(Dynamic dynamic)
Is dynamic an ottava (8va, 8vb, 15va or 15vb)?
booleanDynamicIsPedal(Dynamic dynamic)
Is dynamic an pedal (Ped.
booleanDynamicIsTempo(Dynamic dynamic)
Is dynamic a Tempo?
booleanDynamicIsVelocity(Dynamic dynamic)
Is dynamic a velocity (power) change?
tableElementsToTable(...)
Transforme a list (multiple returned values from a function call) to a table.
booleanEnsureObjectInStaffArea(Score score, Staff staff, obj)
Ensure an object is in the Staff area, move it vertically if needed.
string, int, int, stringEnterFont(string font, face, number size, string color)
Ask the user to choose font, face, size and color using the built-in EditTextStyle() dialog.
numberEnterNumber(string text, number defaultValue, number minValue, number maxValue)
Ask the user to enter a number.
number, numberEnterXY(string prompt, number minX, number maxX, number stepX, number factoryX, number currentX, number minY, number maxY, number stepY, number factoryY, number currentY, string displayValuesMask)
Ask to enter X,Y coordinates in a plotter with X and Y axis.
string, stringFontFaceNumberToString(int face)
Convert a font face (sum of FACE_* constants from MSDefine) to strings.
intFontFaceStringToNumber(string str)
Convert a font face as string like "BI" into sum of FACE_* constants from MSDefine.
tableGetBarVisibilityState(Score score, int firstBar, int lastBar)
Get the visibility state of all bars between firstBar and lastBar.
tableGetChordsFromStaff(Score score, Staff staff, boolean held)
Get the chords of a Staff from the chord line and return detailed informations.
CollectionGetDynamicsThatApplyToStaff(Score score, Staff staff)
Get all Dynamic that apply to the specified Staff.
 GetGlobalSetting(string settingName, boolean multiple)
Reads a line from global settings file, when MyrScript has no built-in function to get the value of a global setting.
KeySignatureGetKeySignatureAtBar(Staff staff, int barN, boolean visibleOnly)
Get the key signature at requested bar of requested staff.
table, intGetMergedStaves(Staff staff)
Get all staves merged with staff, included.
table, intGetOverlappingSymbols(Symbol sym)
Get all symbols (notes and rests) from merged staves, which begin time is before sym end time, and end time is after sym begin time.
string, int, int, stringGetPreferredFont(string object)
Get preferred font from Global settings > Fonts
tableGetStavesGroups(Score score, Staff staff)
Get all StavesGroups of the score or containing staff if this argument is provided.
tableGetStavesInGroup(StavesGroup sg)
Return an array of staves in StavesGroup sg
table, intGetSymbolsInChord(Symbol sym)
Return all symbols in chord with sym (included), in its staff and merged ones.
number, int, DynamicGetTempoAtTime(Score score, int time)
Get tempo value and its Dynamic object (if applicable) at specified time of the score
 IF(boolean expr, a, b)
Short and safe way to write ternary expression.
booleanIN(term, ...)
Check if term is in the list of following arguments.
 IncludeOnce(string file)
Include file only and only if it hasn't been included before.
 InsertReservedPages(Score score)
Insert reserved pages, after the already existing if any) and shift the free objects to next pages.
booleanInstrumentIsUsed(Score score, Instrument instr, boolean excludeMutedStaves)
Is instr Instrument used in score ?
booleanIsLuaClass(string className)
Is className the name of a class?
booleanIsPowerOfTwo(number n)
Is n a number power of 2?
booleanIsScreenReaderActive()
Is there a screen reader, a voice that assist visually impaired user?
booleanIsThemeSoundsActive()
Are interface sounds active in scripts using SMDialog and SMMenu?
 JumpAndSelectBar(Score score, int barN, Staff staffBegin, Staff stafEnd)
Jump to the requested bar number and select it, all staves or the requested staff if not nil.
numberLinearScaling(number x, number a, number b, number c, number d)
Linear scaling (or linear transformation) of \(x\) from range \([a,b]\) to \([c,d]\).
intLoadScoreAppearance(Score score, string setName)
Load score appearance settings from a file saved by SaveScoreAppearance(...).
tableMenuMultipleChoice(string title, Lexicon lexicon, datas, int minNbOfChoice, int maxNbOfChoice, string header)
Menu to pick multiple value in a list of items as checkboxes.
 MenuSingleChoice(string title, Lexicon lexicon, datas, string header, boolean hideRadios)
Menu to pick one value in a list of items as radio buttons.
tableMidiGetEventFiltered(boolean allowNoteOn, boolean allowNoteOff, boolean allowCC, boolean allowProgramChange, boolean allowAftertouch, boolean allowPitchBend, boolean allowOthers, int delay, table allowedSources)
Apply a filter to Midi.GetEvent to exclude some Midi messages and return all events since last call.
 MidiSendCC(int interface, int channel, int controller, int value)
Send a control change (CC) message to a MIDI device.
 MuteScreenReader(int delay)
Temporarily mute the Screen Reader for a short delay.
booleanNAND(boolean ...)
NAND (NOT AND) function in boolean algebra, that accepts undefined number of arguments and returns true if at least one argument is not true.
booleanNIL(...)
Return true if all arguments are nil
booleanNOR(boolean ...)
NOR (NOT OR) function in boolean algebra, that accepts undefined number of arguments and returns true if all arguments are not true.
booleanNOT(boolean b)
NOT function in boolean algebra.
booleanNOT_NIL(...)
Return true if all arguments are not nil
numberNumberOfDecimals(number n)
Get the number of decimals of a number
booleanOR(boolean ...)
OR function in boolean algebra, that accepts undefined number of arguments.
 PlayFromBar(Score score, int barNumber, boolean showKaraoke, boolean scrollMusic, boolean followMusic, int metronomeBars)
Start playing music from specified bar.
 PlayNote(Symbol symbol)
Plays a note, shortcut and fix for Staff.PlayNotes().
 PlayThemeSound(string soundName, boolean wait)
Play a "theme" sound, if set to active.
numberPowerScaling(number x, number n, number a, number b, number c, number d)
Power scaling of \(x\) from range \([a,b]\) to \(x^n\) in \([c,d]\).
numberQuadraticScaling(number x, number a, number b, number c, number d)
Quadratic scaling of \(x\) from range \([a,b]\) to \([c,d]\).
 RecentScriptsAdd(string path, string name)
In debug mode, add current script to the "Recent scripts" list.
 SMAlert(string msg)
Add accessibility to built-in Alert() function.
intSMApplyToAllSelectedSymbols(Score score, function processFunc, boolean excludeSpecials)
Apply a function to all selected symbols, individually selected or continous selection.
intSMApplyToAllSymbols(Score score, staves, int firstBar, int lastBar, function processFunc, boolean excludeSpecials)
Apply a function to all symbols in the score, or staff, or in a range of bars.
booleanSMConfirmation(string msg)
Add accessibility to built-in Confirmation() function.
stringSMEnterString(string text, string defaultValue)
Call to EnterString with accessibility and assertions checks
SymbolSMFirstSelectedSymbol(Score score, Staff staff, boolean ignoreGhostRest)
Returns the first selected symbol (range or individual selection) of the staff or the whole score.
SymbolSMLastSelectedSymbol(Score score, Staff staff, boolean ignoreGhostRest)
Returns the last selected symbol (range or individual selection) of the staff or the whole score.
 SMMessage(string msg, boolean skipVisual)
Add accessibility to built-in Message() function.
string, intSMPitchToString(int pitch, int preferredAccidental, int compatible, string preferredNote)
Extension and bugfix for builtin PitchToString function.
int, intSMStringToPitch(string name)
Extension and bugfix for builtin StringToPitch function.
 SaveScoreAppearance(Score score, string setName, boolean full)
Save score appearance settings in a file.
 ScreenReader(string text, boolean wait)
Say the text if text to speech is enable for visually impaired people (screen reader).
Symbol, StaffSearchNextSymbol(Score score, staves, from, function matcher)
Search next symbol with custom matcher function, in whole score or a list of staves, at a time position or after a symbol.
Symbol, StaffSearchPreviousSymbol(Score score, staves, from, function matcher)
Search previous symbol with custom matcher function, in whole score or a list of staves, at a time position or before a symbol.
stringSerialize(obj)
Serialize an object to store it as string and later deserialization.
 SetDrumGridsDivision(Score score, int numberOfDivisions)
Set the Staff.DefaultDrumDivision to all drum grid-staves.
 SetGhostRestDisplayMode(Score score, int grdm)
Set the ghost rest display mode for all staves in all views.
 SetInstrumentFXProcessor(Instrument instr, FXProcessor fxproc)
Set the default FX Processor for an instrument.
booleanSetSlurDirection(Symbol note, boolean isUp)
Set slur direction up or down.
intShowHiddenClefs(Staff staff)
Show hidden clefs where needed.
booleanSortTargets(Score score)
Sort the targets (rehearsal marks) by bar number.
numberSquareRootScaling(number x, number a, number b, number c, number d)
Square root scaling of \(x\) from range \([a,b]\) to \([c,d]\).
 StaffSetAmbitus(Score score, Staff staff, boolean state)
Set the ambitus enabled or disabled for staff, and also at score's level else ambitus won't display.
stringStavesGroupName(StavesGroup sg)
Return the name (title) of sg or build a name from its first and last grouped staves.
intStorageAreaClear(StorageArea storage, string tag4)
Remove all items from the StorageArea storage for tag tag4.
int, int, boolean, boolean, stringSymbolGetAccidental(Symbol sym)
Return accidental data for a Symbol, handles microtonals.
booleanSymbolIsDotted(Symbol sym)
Tell if the Symbol is displayed with dot(s).
booleanSymbolIsMicrotonalAccidental(Symbol sym)
Is the note played with a microtonal accidental?
booleanSymbolIsTieVisible(Symbol note)
Is the note tied?
booleanSymbolSetAccidentalVisibility(Symbol sym, boolean visible)
Change the accidental visibility of a Symbol.
booleanSymbolsAreContiguous(Symbol a, Symbol b)
Tell if two Symbols are contiguous.
booleanSymbolsCanBeTied(Symbol ...)
Symbols can be tied if they are all contiguous and have same played and displayed pitch.
 TableToElements(table t)
Bugfix version of MSLibrary's PushAllTableElts(t), return all elements of a table as multiple return values.
 TargetHideBarNumbers(Score score)
Hide bar numbers at bar that display a rehearsal mark, for all views.
 TargetSplitMultiRests(Score score)
Split multi-rests at all visible rehearsal marks, for all views.
intTargetVisibility(Score score, Target target, boolean visible)
Turn one or all targets visible or hidden.
 UnMuteScreenReader()
After MuteScreenReader(...) and the massive actions that would have produced unaudible audio messages, unmute the Screen Reader.
booleanXOR(boolean a, boolean b)
XOR function in boolean algebra.
booleanassertBoolean(b, string errorMessage, boolean visual)
Assert b is a boolean (true or false, not nil), else throw errorMessage.
booleanassertDialog(dialog, string errorMessage, boolean visual)
Assert dialog is a Dialog, else throw errorMessage.
booleanassertEquals(expr, expected, string Text, boolean visual)
Assertion an expression or function call equals an expected result.
booleanassertEqualsIgnoreCase(expr, expected, string Text, boolean visual)
Assertion an expression or function call equals an expected result; if both are string, the cases are ignored.
booleanassertExpression(expr, string errorMessage, boolean visual)
Assert an expression result is true.
booleanassertFalse(b, string errorMessage, boolean visual)
Assert b is false, else throw errorMessage.
booleanassertFunction(f, string errorMessage, boolean visual)
Assert f is a function, else throw errorMessage.
booleanassertInArray(value, table t, string text, boolean visual)
Assert a value is found in a table.
booleanassertNegativeNumber(n, string errorMessage, boolean visual)
Assert n is a negative number, else throw errorMessage.
booleanassertNil(n, string errorMessage, boolean visual)
Assert n is nil, else throw errorMessage.
booleanassertNotEmptyString(s, string errorMessage, boolean visual)
Assert s is a not-nil and not empty string, else throw errorMessage.
booleanassertNotNil(n, string errorMessage, boolean visual)
Assert n is not nil, else throw errorMessage.
booleanassertNotZero(n, string errorMessage, boolean visual)
Assert n is a number but not 0, else throw errorMessage.
booleanassertNumber(n, string errorMessage, boolean visual)
Assert n is a not-nil number, else throw errorMessage.
booleanassertPositiveNumber(n, string errorMessage, boolean visual)
Assert n is a positive number, else throw errorMessage.
booleanassertScore(s, string errorMessage, boolean visual)
Assert s is a Score, else throw errorMessage.
booleanassertString(s, string errorMessage, boolean visual)
Assert s is a not-nil string (possibly empty), else throw errorMessage.
booleanassertTable(t, string errorMessage, boolean visual)
Assert t is a table, else throw errorMessage.
booleanassertTrue(b, string errorMessage, boolean visual)
Assert b is true, else throw errorMessage.
booleanassertType(t, string expectedType, string errorMessage, boolean visual)
Assert type(t) is a expectedType, else throw errorMessage.
intbin2int(string s, boolean signed)
Converts binary number (string containing only "0" and "1") to number.
booleanbool(expr)
Converts expr to a boolean.
numberbound(number n, number mini, number maxi)
Ensure number n is within bounds [mini:maxi].
tablecase(string _type, _params, function _func, boolean _break)
Create a case for switch() function.
numbercm_to_dpi72(number n)
Convert a centimeter value into 72 DPI pixels.
tabledefault(function _func)
Create a default case for switch() function.
numberdpi72_to_cm(number n)
Convert a 72 DPI pixel value into centimeters.
numberduration_256th_of_quarter_to_ms(int nbOf256th, number tempo)
Convert 256ths of quarter to milliseconds, according to tempo.
intduration_256th_of_quarter_to_percent_of_note(int nbOf256th, int noteDuration, number tempo)
Convert 256ths of quarter to a percentage of a note duration, according to tempo.
intduration_ms_to_256th_of_quarter(number milliseconds, int noteDuration, number tempo)
Convert at duration in milliseconds to 256th of quarter, according to tempo
intduration_ms_to_note(number milliseconds, number tempo)
Convert a duration in milliseconds to a note duration according to tempo.
intduration_ms_to_percent_of_note(number milliseconds, int noteDuration, number tempo)
Convert a duration in milliseconds to a percentage of a note duration, according to tempo.
numberduration_note_to_ms(int noteDuration, number tempo)
Convert a note duration to milliseconds, according to tempo.
intduration_percent_of_note_to_256th_of_quarter(int nbOf256th, int noteDuration, number tempo)
Convert a percentage of a note duration to 256ths of quarter, according to tempo.
numberduration_percent_of_note_to_ms(int percent, int noteDuration, number tempo)
Convert a percentage of note duration to milliseconds, according to tempo.
numberflag_clear(number set, number flag)
Clear a bit to 0, the bit can be seen as a flag.
numberflag_set(number set, number flag)
Set a bit to 1, the bit can be seen as a flag.
booleanflag_test(number set, number flag)
Test if a bit is set, the bit can be seen as a flag.
stringgettagname(obj)
Return, if known, the tag name of an object.
inthex2int(string s, boolean signed)
Converts hexadecimal number (string containing 0-9a-fA-f) to number.
booleanisTable(obj)
Returns true if obj is a table or a MyrScript object represented as a table such as Score or Target.
 longest_common_subsequence(a, b)
Longest Common Subsequence (LCS) algorithm, basis for data comparison.
numberround(number num, int numberOfDecimals)
Round a number.
 switch(term, table cases)
switch..case.
 table_insert_multi(table t, ...)
Insert multiple items in a table in one call.
tabletable_unique(table tab)
Remove duplicates from a table
 tdebug(...)
Return the structure of a table, Collection or Map for debugging to the console.
 throw(string exception, boolean visual, function catch)
Log (console and/or file) and stop the script with error().
stringtobin(int n, int size, string separator)
Converts a number to a binary string (containing only 0 and 1)
stringtohex(int n, int size, string separator)
Converts a number to hexadecimal string Shortcut to format("%x", n) with more options and no 32-bit limit

Constants

int BAR_STATE_UNDEFINED

Bar visibility state: undefined: should not happen.

int BAR_STATE_VISIBLE

Bar visibility state: normal, visible.

int BAR_STATE_MULTI_FIRST

Bar visibility state: visible, first bar of a multi-rest or multi-repeat.

int BAR_STATE_MULTI_MIDDLE

Bar visibility state: not visible, inside (but not last bar of) a multi-rest or multi-repeat.

int BAR_STATE_MULTI_LAST

Bar visibility state: not visible, last bar of a multi-rest or multi-repeat.

int BAR_STATE_BEFORE_PRINT_REGION

Bar state visibility: not visible, before first printed bar

int BAR_STATE_AFTER_PRINT_REGION

Bar state visibility: not visible, after last printed bar

Functions

IncludeOnce(string file)

Include file only and only if it hasn't been included before.

For that, you must always use IncludeOnce instead of Include. Include is safe and fast for simple script that create constants and functions, but may load the CPU if included file performs heavy tasks.

ParameterTypeDefaultDescription
filestring Filename to include, file extension is not mandatory.
Usage

IncludeOnce("SMStructureReader")

throw(string exception, boolean visual, function catch)

Log (console and/or file) and stop the script with error().

Inspired from Java's throw new Exception(...) with a function as 'catch' mechanism.

ParameterTypeDefaultDescription
exceptionstring Error message
visualbooleanfalseVisual alert. If true, does not stop the script with a console error. Your script must handle this to stop gracefully.
catchfunctionnilIf present, call this function. If catch() returns true, the script is stopped, else it continues at your own risks.
See
err

assertNumber(n, string errorMessage, boolean visual)

Assert n is a not-nil number, else throw errorMessage.

ParameterTypeDefaultDescription
n  n
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected number, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will stop with a console error message.
See
assertPositiveNumber
assertNegativeNumber
assertNotZero

assertPositiveNumber(n, string errorMessage, boolean visual)

Assert n is a positive number, else throw errorMessage.

ParameterTypeDefaultDescription
n  n
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected positive number, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
See
assertNumber
assertNegativeNumber
assertNotZero

assertNegativeNumber(n, string errorMessage, boolean visual)

Assert n is a negative number, else throw errorMessage.

ParameterTypeDefaultDescription
n  n
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected negative number, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
See
assertNumber
assertPositiveNumber
assertNotZero

assertNotZero(n, string errorMessage, boolean visual)

Assert n is a number but not 0, else throw errorMessage.

ParameterTypeDefaultDescription
n  n
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected not-zero number, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
See
assertNumber
assertPositiveNumber
assertNegativeNumber

assertString(s, string errorMessage, boolean visual)

Assert s is a not-nil string (possibly empty), else throw errorMessage.

ParameterTypeDefaultDescription
s  s
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected string, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
See
assertNotEmptyString

assertNotEmptyString(s, string errorMessage, boolean visual)

Assert s is a not-nil and not empty string, else throw errorMessage.

ParameterTypeDefaultDescription
s  s
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected not-empty string, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
See
assertString

assertBoolean(b, string errorMessage, boolean visual)

Assert b is a boolean (true or false, not nil), else throw errorMessage.

ParameterTypeDefaultDescription
b  b
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected boolean, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
See
assertTrue
assertFalse
assertExpression

assertTrue(b, string errorMessage, boolean visual)

Assert b is true, else throw errorMessage.

ParameterTypeDefaultDescription
b  b
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected true, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
See
assertFalse
assertNotNil
assertExpression

assertFalse(b, string errorMessage, boolean visual)

Assert b is false, else throw errorMessage.

Note: if you check a expression, e.g. x < y, Lua returns nil if the comparaison fails, instead of false.

ParameterTypeDefaultDescription
b  b
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected false, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
See
assertTrue
assertNil
assertExpression

assertTable(t, string errorMessage, boolean visual)

Assert t is a table, else throw errorMessage.

ParameterTypeDefaultDescription
t  t
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected table, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.

assertFunction(f, string errorMessage, boolean visual)

Assert f is a function, else throw errorMessage.

ParameterTypeDefaultDescription
f  f
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected function, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.

assertNil(n, string errorMessage, boolean visual)

Assert n is nil, else throw errorMessage.

ParameterTypeDefaultDescription
n  n
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected nil, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
See
assertNotNil
assertFalse
assertExpression

assertNotNil(n, string errorMessage, boolean visual)

Assert n is not nil, else throw errorMessage.

ParameterTypeDefaultDescription
n  n
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected not nil, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
See
assertNil
assertTrue
assertExpression

assertExpression(expr, string errorMessage, boolean visual)

Assert an expression result is true.

This is the equivalent of Lua assert function with more logging.

ParameterTypeDefaultDescription
expr  Result of an expression, e.g. x < y
errorMessagestring Nothing is concatenated, the message must be full and self-explainatory.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
See
assertTrue
assertNotNil

assertEquals(expr, expected, string Text, boolean visual)

Assertion an expression or function call equals an expected result.

This is useful for unit tests.

ParameterTypeDefaultDescription
expr  Result of an expression
expected  Expected result
Textstring to print on console and throw if expr ~= expected
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
Error
If expr ~= expected

assertEqualsIgnoreCase(expr, expected, string Text, boolean visual)

Assertion an expression or function call equals an expected result; if both are string, the cases are ignored.

This is useful for unit tests.

ParameterTypeDefaultDescription
expr  Result of an expression
expected  Expected result
Textstring to print on console and throw if expr ~= expected
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
Error
If <strlower(expr) ~= strlower(expected)

assertInArray(value, table t, string text, boolean visual)

Assert a value is found in a table.

ParameterTypeDefaultDescription
value  number or string. nil always fails the assertion.
ttable List of values in which value is searched for.
textstring Text to print on console and throw if expr ~= expected
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
Error
If value not found in t

assertDialog(dialog, string errorMessage, boolean visual)

Assert dialog is a Dialog, else throw errorMessage.

ParameterTypeDefaultDescription
dialog  dialog
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected Dialog, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.

assertScore(s, string errorMessage, boolean visual)

Assert s is a Score, else throw errorMessage.

ParameterTypeDefaultDescription
s  s
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected Score, got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.

assertType(t, string expectedType, string errorMessage, boolean visual)

Assert type(t) is a expectedType, else throw errorMessage.

ParameterTypeDefaultDescription
t  t
expectedTypestring expectedType
errorMessagestring Message to throw: by convention, the function where it happen, and the argument's or variable's name.
": expected 'expectedType', got ..." will be concatenated.
visualbooleanfalseVisual alert. Does not stop the script with a console error message, returns true if assertion is correct, nil if it fails.
Your script must handle the returned value to stop gracefully.
Return
boolean: true if assertion is correct, nil (for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
See
assertDialog
assertFunction
assertNumber
assertScore
assertString
assertTable
Example

assertType(s, "Staff", "MyFunction, argument #1")
 --> if s is not a Staff, this print
 --> ERROR MyFunction, argument #1, expected Staff, got ...

bool(expr)

Converts expr to a boolean.

expr can be a number, an expression or a string. This a convenient way to ensure that the result of an expression is never nil where it may cause troubles or unknown behaviour: myDialogItem.IsVisible = bool(a_long_expression) is a syntaxic sugar for myDialogItem.IsVisible = (a_long_expression) or false

ParameterTypeDefaultDescription
expr  expression, number, string...
Return
boolean: true if expr == true or expr == "1", false otherwise.
Example


 print(bool(nil)) --> 0
 print(bool(3)) --> 0
 print(bool("hello")) --> 0
 print(bool(1 == 3)) --> 0
 print(bool(3 < 7)) --> 1
 print(bool("1")) --> 1

NOT(boolean b)

NOT function in boolean algebra.

Lua not x means "not nil", so not true is always true. NOT(true) returns nil (for false) so it can be used safely in if..then statements. If you want to obtain a real false, use the bool() function: a = bool(NOT(<expression>))

ParameterTypeDefaultDescription
bboolean b
Return
boolean:
  • true if b==nil or b==false
  • ,
  • nil (for false) otherwise.

AND(boolean ...)

AND function in boolean algebra, that accepts undefined number of arguments.

Arguments that are not booleans are considered as false: AND(true,"123") returns nil.

ParameterTypeDefaultDescription
...boolean Undefined number of arguments.
Return
boolean:
  • true if all arguments are true
  • nil (for false) if at least one argument is not true.
Error
if less than two arguments

OR(boolean ...)

OR function in boolean algebra, that accepts undefined number of arguments.

Arguments that are not booleans are ignored: OR("abc","123") returns nil

ParameterTypeDefaultDescription
...boolean Undefined number of arguments.
Return
boolean:
  • true if at least one argument is true
  • nil (for false) if no argument is true.
Error
if less than two arguments

NAND(boolean ...)

NAND (NOT AND) function in boolean algebra, that accepts undefined number of arguments and returns true if at least one argument is not true.

Arguments that are not booleans are considered as false: NAND(true,"123") returns true.

ParameterTypeDefaultDescription
...boolean Undefined number of arguments.
Return
boolean:
  • true if at least one argument is not true,
  • nil (for false) if all arguments are true.
Error
if less than two arguments

NOR(boolean ...)

NOR (NOT OR) function in boolean algebra, that accepts undefined number of arguments and returns true if all arguments are not true.

Arguments that are not booleans are considered as false: NOR("abc","123") returns true.

ParameterTypeDefaultDescription
...boolean Undefined number of arguments.
Return
boolean:
  • true if all arguments are not true,
  • nil (for false) if at least one argument is true.
Error
if less than two arguments

XOR(boolean a, boolean b)

XOR function in boolean algebra.

ParameterTypeDefaultDescription
aboolean a
bboolean b
Return
boolean:
  • true if only one of a and b is true,
  • nil (for false) if a and b have same boolean value.

NIL(...)

Return true if all arguments are nil

ParameterTypeDefaultDescription
...  ...
Return
boolean:
  • true if all arguments are nil,
  • nil (for false) if at least one argument is not nil.

NOT_NIL(...)

Return true if all arguments are not nil

ParameterTypeDefaultDescription
...  ...
Return
boolean:
  • true if all arguments are not nil,
  • nil (for false) if at least one argument is nil.

IF(boolean expr, a, b)

Short and safe way to write ternary expression.

C-language: result = expr ? a : b;
Lua / MyrScript: result = expr == true and a or b
In a spreadsheet cell: =IF(expr;a;b) So here is Lua syntaxic sugar: result = IF(expr, a, b).

ParameterTypeDefaultDescription
exprboolean expr
a  a
b  b
Return
a if expr is true, else b.
Error
if expr is not a boolean

IN(term, ...)

Check if term is in the list of following arguments.

ParameterTypeDefaultDescription
term  string, number or objects that support == comparison
...  List of arguments, of undefined length. If one (or more) arguments are table, Collection or Map then term is searched in their items.
Note that Collection and Map values must have the same type than type(term).
Return
boolean: true if the list contains term, nil (for false) if the list doesn't contains term
See
ArrayContains

CompareVersions(string a, string b)

Compare two version numbers in x.y.z string format.

ParameterTypeDefaultDescription
astring a
bstring b
Return
string: "<", ">" or "=" if a is lower, greater or equal to b.
Example

CompareVersions("9.9.7", "9.9.6") --> ">"

CompareMyrScriptVersion(string version)

Is MyrScript =, < or > version x.y.z?

As Application.MyrScriptVersion is a string, comparison may fail in the future, "10.1.1" is greater than "9.9.9" but string comparison will stay it's lower (because "1" < "9").

ParameterTypeDefaultDescription
versionstring Version to compare, in x.y.z form (e.g.: "1.6.9")
Return
string: "<", ">" or "=" if Application.MyrScriptVersion is lower, greater or equal to version.

PlayFromBar(Score score, int barNumber, boolean showKaraoke, boolean scrollMusic, boolean followMusic, int metronomeBars)

Start playing music from specified bar.

Target.PlayMusic() is bogus; here is a work-around.

ParameterTypeDefaultDescription
scoreScore The score to play
barNumberint The bar to start from, could be Target.Bar
showKaraokebooleanuser prefsDisplay karaoke if score has lyrics?
scrollMusicbooleanuser prefsScrolls the score while playing?
followMusicbooleanuser prefsOpen follow tune dialog?
metronomeBarsintuser prefsNumber of metronome bars to play before the music
Usage

PlayFromBar(FrontScore(), 2)

DeleteAllTargets(Score score, boolean preserveScore)

Delete all targets (rehearsal marks) from a score.

ParameterTypeDefaultDescription
scoreScore score
preserveScorebooleanfalsePreserve an undo?
Return
int: Number of deleted targets

SortTargets(Score score)

Sort the targets (rehearsal marks) by bar number.

Targets may be sorted by creation date in your score, if the last inserted is B between A and C, order is A, C, B. Thiis function sorts by deleting and recreating targets as A, B, C.

ParameterTypeDefaultDescription
scoreScore score
Return
boolean: false if no sort was needed, true if sort was done.
Usage

SortTargets(FrontScore())

isTable(obj)

Returns true if obj is a table or a MyrScript object represented as a table such as Score or Target.

ParameterTypeDefaultDescription
obj  obj
Return
boolean: boolean

ArrayClear(table t)

Optimization of clearing a table.

tremove is time consuming because it shift all items after the removed one.
tremove from last to first would be a bit faster.
but setting items to nil is even faster.

ParameterTypeDefaultDescription
ttable The table to clear.

ArrayContains(table tab, term)

Does tab contains term?

ParameterTypeDefaultDescription
tabtable A table of numbers or strings
term  A number or a string to find in tab
Return
boolean: true, or nil (for false)
Error
if tab's items are not comparable with term

gettagname(obj)

Return, if known, the tag name of an object.

When a tag is created and attached to a table by settag(myTable, tag(MyClass)), this method retrieves the MyClass name.

ParameterTypeDefaultDescription
obj  A Lua object
Return
string: The tag name, nil if not found.
Example

local c = Collection:new("string")
 print(gettagname(c)) --> "Collection"
 print(gettagname("Hello world")) --> "string"
 print(gettagname(FrontScore().FirstStaff)) --> Staff

IsLuaClass(string className)

Is className the name of a class?

Class is a table with a tag, and a :new(...) method.
Symbol, Staff or Score are not Lua class, Interval, Collection and SMDialog are.

ParameterTypeDefaultDescription
classNamestring className
Return
boolean: true if it's a class, nil for false if not.
Example

print(IsLuaClass("table")) --> nil
 print(IsLuaClass("Collection")) --> 1

tdebug(...)

Return the structure of a table, Collection or Map for debugging to the console.

ParameterTypeDefaultDescription
...  Structure(s) to debug

switch(term, table cases)

switch..case.

Keyword switch doesn't exist in Lua? Here it is. Each case can test more things than C-like equals: equals, not equals, comparison (greater, lower), in a table, between two values (range). See SwitchCaseTest() for examples. Note that it creates tables, so switch is not best solution in huge loops where a set of if..elseif..elseif..end can do the job faster.

ParameterTypeDefaultDescription
term  string or number, that can be compared
casestable Table of cases created by case() and default() functions.
Return
a value if cases' "body" functions return a value.
See
case
default
Usage

switch(term, { case(...), case(...), default(...) }).
Example
local result = switch(my_number, {
			case("<", 0, function(term) print(term.." is negative") return "negative" end),
			case("eq", 2, function(term) print(term.." = two") return "=2" end, false),
			case("in", {3,5,7,11,13,17}, function(term) print(term.." is a prime") return "prime" end),
			case("range", {20,29}, function(term) print("20 <= "..term.." <= 29") return "between 20 and 29" end),
			default( function(term) print(term.." doesn't match any case, this is default") return "The answer is... 42" end)
		})

case(string _type, _params, function _func, boolean _break)

Create a case for switch() function.

ParameterTypeDefaultDescription
_typestring Accepted values are:
  • "=", "==", "eq" for equals,
  • "~=", "!=", "~eq", "!eq" for not equals,
  • "<", "<=", ">", ">=", "lt", "le", "gt", "ge" for comparison,
  • "in", "!in" to check if in an array of values,
  • "range", "!range" to check if between two values.
_params  A number, a string, or a table:
  • For "in" and "!in", table can have 1 to n items.
  • For "range" and "!range"; table must have 2 items.
_funcfunction _func
_breakbooleantruetrue to stop after this case, false to continue and execute function of next case(s) until a case breaks.
Return
table: a case for switch() function
See
switch
switch

default(function _func)

Create a default case for switch() function.

ParameterTypeDefaultDescription
_funcfunction that will receive the tested term as parameter
Return
table: a case for switch() function
See
switch
switch

CopyFXProcessor(FXProcessor source, FXProcessor dest)

Copy all parameters from a FXProcessor to another one.

ParameterTypeDefaultDescription
sourceFXProcessor The FXProcessor to copy
destFXProcessor The destination FXProcessor that will receive source settings.
Error
if source or dest are nil

SetInstrumentFXProcessor(Instrument instr, FXProcessor fxproc)

Set the default FX Processor for an instrument.

The instrument's FXProcessor is not visible on the score. It's the one you edit from the instrument dialog's "FX" button.

ParameterTypeDefaultDescription
instrInstrument The instrument
fxprocFXProcessor The FXProcessor which properties will be copied in the instrument's FX Processor

SMApplyToAllSelectedSymbols(Score score, function processFunc, boolean excludeSpecials)

Apply a function to all selected symbols, individually selected or continous selection.

MSLibrary's ApplyToAllSelectedSymbols(...) function doesn't handle individually selected symbols, and browse from last to first, which is safe for symbol deletion. This customized browse selected notes on all staves from first to last, not convenient for deletion. It can skips ghost rests and special symbols, handles individual and continuous (range) selection.

ParameterTypeDefaultDescription
scoreScore score
processFuncfunction Function with two Symbol and Staff arguments, which returns true (= 1) if symbol has been processed, -1 to stop the process. Other returned values are ignored, process continue to next symbol.
excludeSpecialsbooleanfalseExclude ghost rest, mesure repeat (%, %2, %4), and unison in divisi (//)?
Return
int: Number of processed symbols
Error
if score is not a Score or processFunc is not a function.
See
SMApplyToAllSymbols

SMApplyToAllSymbols(Score score, staves, int firstBar, int lastBar, function processFunc, boolean excludeSpecials)

Apply a function to all symbols in the score, or staff, or in a range of bars.

ParameterTypeDefaultDescription
scoreScore score
staves nil
  • nil means all staves
  • a Staff object to apply only to that staff
  • a table of Staff to apply to a list of staves
firstBarint1First bar to start applying the function.
lastBarintscore.NumberOfBarsLast bar to stop applying the function.
processFuncfunction Function with two Symbol and Staff arguments, which returns true (= 1) if symbol has been processed, -1 to stop the process. Other returned values are ignored, process continue to next symbol.
excludeSpecialsbooleanfalseExclude ghost rests, bar repeats (%, %2, %4) and unison in divisi (//)?
Return
int: Number of processed symbols
Error
if arguments have wrong types.
See
SMApplyToAllSelectedSymbols

PlayNote(Symbol symbol)

Plays a note, shortcut and fix for Staff.PlayNotes().

Play only one note (the symbol parameter), in its context (tempo at its Time position), duration, velocity and pitch. Fix the no-sound bug when pitch==0 on grid drum staves.

ParameterTypeDefaultDescription
symbolSymbol (note) to play

SetDrumGridsDivision(Score score, int numberOfDivisions)

Set the Staff.DefaultDrumDivision to all drum grid-staves.

ParameterTypeDefaultDescription
scoreScore score
numberOfDivisionsint Number of division per beat
Error
if score is nil or numberOfDivisions < 1

round(number num, int numberOfDecimals)

Round a number.

ParameterTypeDefaultDescription
numnumber Number to round()
numberOfDecimalsint0Number of decimals
Return
number: the rounded number, i.e. floor(number + 0.5) for an integer (no decimals)

NumberOfDecimals(number n)

Get the number of decimals of a number

ParameterTypeDefaultDescription
nnumber n
Return
number: number

bound(number n, number mini, number maxi)

Ensure number n is within bounds [mini:maxi].

bound(n, mini, maxi) is a syntaxic sugar for max(min(n, maxi), mini)

ParameterTypeDefaultDescription
nnumber n
mininumber Minimal value
maxinumber Maximal value
Return
number: Bounded n.

dpi72_to_cm(number n)

Convert a 72 DPI pixel value into centimeters.

ParameterTypeDefaultDescription
nnumber n
Return
number: number

cm_to_dpi72(number n)

Convert a centimeter value into 72 DPI pixels.

ParameterTypeDefaultDescription
nnumber n
Return
number: number

duration_note_to_ms(int noteDuration, number tempo)

Convert a note duration to milliseconds, according to tempo.

ParameterTypeDefaultDescription
noteDurationint noteDuration
temponumber tempo
Return
number: Rounded to 3 decimals
Error
if noteDuration is nil, if tempo is nil or <= 0

duration_ms_to_note(number milliseconds, number tempo)

Convert a duration in milliseconds to a note duration according to tempo.

ParameterTypeDefaultDescription
millisecondsnumber milliseconds
temponumber tempo
Return
int: A note duration, comparable to DURATION_QUARTER and other constants in MSDefine
Error
if milliseconds is nil, or tempo is nil or <= 0

duration_percent_of_note_to_ms(int percent, int noteDuration, number tempo)

Convert a percentage of note duration to milliseconds, according to tempo.

ParameterTypeDefaultDescription
percentint percent
noteDurationint noteDuration
temponumber tempo
Return
number: Rounded to 3 decimals
Error
if percent is nil, if noteDuration is nil, if tempo is nil or <= 0

duration_ms_to_percent_of_note(number milliseconds, int noteDuration, number tempo)

Convert a duration in milliseconds to a percentage of a note duration, according to tempo.

ParameterTypeDefaultDescription
millisecondsnumber milliseconds
noteDurationint noteDuration
temponumber tempo
Return
int: Percent of noteDuration
Error
if milliseconds is nil, if noteDuration is nil, if tempo is nil or <= 0

duration_256th_of_quarter_to_ms(int nbOf256th, number tempo)

Convert 256ths of quarter to milliseconds, according to tempo.

ParameterTypeDefaultDescription
nbOf256thint nbOf256th
temponumber tempo
Return
number: Rounded to 3 decimals
Error
if nbOf256th is nil, if tempo is nil or <= 0

duration_ms_to_256th_of_quarter(number milliseconds, int noteDuration, number tempo)

Convert at duration in milliseconds to 256th of quarter, according to tempo

ParameterTypeDefaultDescription
millisecondsnumber milliseconds
noteDurationint noteDuration
temponumber tempo
Return
int: 256th of quarter
Error
if milliseconds is nil, if noteDuration is nil, if tempo is nil or <= 0

duration_256th_of_quarter_to_percent_of_note(int nbOf256th, int noteDuration, number tempo)

Convert 256ths of quarter to a percentage of a note duration, according to tempo.

ParameterTypeDefaultDescription
nbOf256thint nbOf256th
noteDurationint noteDuration
temponumber tempo
Return
int: int
Error
if nbOf256th is nil, if noteDuration is nil, if tempo is nil or <= 0

duration_percent_of_note_to_256th_of_quarter(int nbOf256th, int noteDuration, number tempo)

Convert a percentage of a note duration to 256ths of quarter, according to tempo.

ParameterTypeDefaultDescription
nbOf256thint nbOf256th
noteDurationint noteDuration
temponumber tempo
Return
int: int
Error
if nbOf256th is nil, if noteDuration is nil, if tempo is nil or <= 0

GetTempoAtTime(Score score, int time)

Get tempo value and its Dynamic object (if applicable) at specified time of the score

ParameterTypeDefaultDescription
scoreScore score
timeint Symbol.Time, Score.TimeBeginSelection
Returns
number: Tempo value (floatting point number)
int: Reference note length, DURATION_QUARTER for general tempo
Dynamic: nil if no tempo was added to the score, i.e. the returned value is general tempo
Error
if score is nil

GetDynamicsThatApplyToStaff(Score score, Staff staff)

Get all Dynamic that apply to the specified Staff.

Dynamics are:

  • velocity changes (crescendo, decrescendo, pppp to fff)
  • Tempo change
  • Pedal on/off
  • Ottava

ParameterTypeDefaultDescription
scoreScore score
staffStaff staff
Return
Collection: of Dynamics that apply to staff are on attached to it, or one of merged staves with it, or one of the staves of the group, or to the whole score.
Error
if score or staff are nil

DynamicIsTempo(Dynamic dynamic)

Is dynamic a Tempo?

ParameterTypeDefaultDescription
dynamicDynamic dynamic
Return
boolean: true if dynamic.Type==DYNAMIC_TEMPO

DynamicIsOttava(Dynamic dynamic)

Is dynamic an ottava (8va, 8vb, 15va or 15vb)?

ParameterTypeDefaultDescription
dynamicDynamic dynamic
Return
boolean: true if dynamic is 8va, 8vb, 15va or 15vb

DynamicIsPedal(Dynamic dynamic)

Is dynamic an pedal (Ped.

or *)?

ParameterTypeDefaultDescription
dynamicDynamic dynamic
Return
boolean: true if dynamic is Ped. or *

DynamicIsVelocity(Dynamic dynamic)

Is dynamic a velocity (power) change?

ParameterTypeDefaultDescription
dynamicDynamic dynamic
Return
boolean: true if dynamic is crescendo, decrescendo, ppp to fff... i.e. not a pedal, not a tempo, not a ottava

SMPitchToString(int pitch, int preferredAccidental, int compatible, string preferredNote)

Extension and bugfix for builtin PitchToString function.

  • Allow pitches out of 0..127 bounds, but keep in mind that HA can't handle them!
  • PitchToString(11) gives 11, SMPitchToString(11) returns B-1
Does not handle microtonal accidentals.

ParameterTypeDefaultDescription
pitchint pitch
preferredAccidentalintAUTOPreferred accidental in MSDefine. HA can handle A## and Bbb as note names. If a string is provided, then if it contains a "b" or a "#", it's interpreted as FLAT or SHARP constants.
compatibleintffalseIf true return value that HA can handle, 11 instead of B-1, a value in bounds.
preferredNotestring""English note "A" to "G", if no preferred accidental or AUTO, select the enharmonic from the preferred note. If result is "A" and preferred note is "G" then result will be "G##", unless allowDoubleAccidental is false.
Returns
string: Anglo-saxon note name followed by octave, e.g. "Ab5".
int: Accidental for the note, one of MSDefine NATURAL,FLAT,SHARP,DOUBLE_FLAT,DOUBLE_SHARP constants.

SMStringToPitch(string name)

Extension and bugfix for builtin StringToPitch function.

Does not handle microtonal accidentals.

  • Allow pitches out of 0..127 bounds
  • StringToPitch("B-1") gives the strange 71 result, SMStringToPitch("B-1") returns 11
  • Handles double-sharp (## or x) and double-flat (bb)

ParameterTypeDefaultDescription
namestring English not name followed by octave. If octave is missing, considers it's the 4th octave.
Returns
int: May be out of 0..127 range.
int: Preferred accidental, one of AUTO, SHARP, FLAT... constants from MSDefine

GetChordsFromStaff(Score score, Staff staff, boolean held)

Get the chords of a Staff from the chord line and return detailed informations.

This is useful to build bass and chords accompaniments, perform analysis, or whatever you want.
The returned structure is a table, indexed from 1 to number of chords. Each element is a table which contains properties:

  • Chord: a Chord object, able to parse more complex notations than HA. From this object, you can obtain the list of notes, chord octave, bass octave (2 octaves lower), inversion...
  • BarNumber: the bar number where the chord is writed
  • TimeBegin: time (in tick, from the beginning of the score), where the chord starts to play
  • TimeEnd: time (in ticks, from the beginning of the score), where the chord ends, just before next chord or an empty cell/bar.
  • ArppegioDelay: by default, staff.ChordArpeggioDelay. May change if [Annn] command has been encountered in chord line.

ParameterTypeDefaultDescription
scoreScore score
staffStaff staff
heldbooleannilHold chord until next is encountered? If nil, use the chord line setup of the staff. HA needs underscore (_) to hold a chord, but this is unsightly for printing, and works randomly.
Return
table: table
See
Chord for more details about Chord object.
Example

local chords = GetChordsFromStaff(FrontScore(), FrontScore().FirstStaff)
 for i=1,getn(chords) do
   print("Chord #" .. i .. ": "..chords[i].Chord:toASCIIName())
   print("Bar #" .. chords[i].BarNumber)
   print(tdebug(chords[i].Chord:notes()))
 end

GetGlobalSetting(string settingName, boolean multiple)

Reads a line from global settings file, when MyrScript has no built-in function to get the value of a global setting.

ParameterTypeDefaultDescription
settingNamestring settingName
multiplebooleanfalseIf false, first line starting with settingName then return it, if true, return all lines that start with settingName in a table.
Return
  • A table if multiple = true,
  • A string if multiple = false and the setting is found,
  • nil if multiple = false and no setting is found.
Example


 local tab = GetGlobalSetting("tabPredefNuances", true)
 --> {"tabPredefNuances 0 20", "tabPredefNuances 1 40", ...}
 local ppp = GetGlobalSetting("tabPredefNuances 0") --> 20
 local pp = GetGlobalSetting("tabPredefNuances 1") --> 40

GetPreferredFont(string object)

Get preferred font from Global settings > Fonts

ParameterTypeDefaultDescription
objectstring One of the items in the global settings dialog in English: "Staff name", "Break text", "Tempo", "Rules names", "Effects & ornaments", "Tablature key", "Tablature grace note", "Tablature note", "Chord grid name", "Chord grid display", "Chord grid summary", "Key summary", "Karaoke line", "Ruler", "Help window", "Array", "Pop up menus"
Returns
string: Font name, or nil if not found
int: Face, or nil if not found
int: Size, or nil if not found
string: color in RGB format, "000000" for now as it may be impossible to parse.

InstrumentIsUsed(Score score, Instrument instr, boolean excludeMutedStaves)

Is instr Instrument used in score ?

Instument.IsUsed returns true even if applide to rule that is never used, or used by a staff that has Virtual Singer voice active. This function handles these cases.

ParameterTypeDefaultDescription
scoreScore score
instrInstrument instr
excludeMutedStavesbooleanfalse 
Return
boolean: boolean

SMEnterString(string text, string defaultValue)

Call to EnterString with accessibility and assertions checks

ParameterTypeDefaultDescription
textstring The prompt text
defaultValuestring""A default value
Return
string: The entered text or nil if user canceled.

EnterNumber(string text, number defaultValue, number minValue, number maxValue)

Ask the user to enter a number.

Use EnterString(...), and checks that the entered is a number within bounds. In case of error, ask again.

ParameterTypeDefaultDescription
textstring Text to dispaly in prompt popup
defaultValuenumbernilA pre-defined value, or nil to force user to enter a value.
minValuenumbernilIf specified, entered value is bound by min and max.
maxValuenumbernilIf specified, entered value is bound by min and max.
Return
number: or nil if user cancelled the choice.

EnterXY(string prompt, number minX, number maxX, number stepX, number factoryX, number currentX, number minY, number maxY, number stepY, number factoryY, number currentY, string displayValuesMask)

Ask to enter X,Y coordinates in a plotter with X and Y axis.

It's handy when you ask for 2 values, as X and Y offsets.

See sample code below

ParameterTypeDefaultDescription
promptstring A prompt text above the plotter, nil means no prompt text.
minXnumber0Minimal value for X
maxXnumber0Maximal value for X
stepXnumber1Step between two consecutive X possible values. e.g. 1 for a value from 0 to 127, 0.01 for fine adjustement of object position in the score... The bigger the faster mouse wheel and keyboard will change the value.
factoryXnumbercurrentXDefault (factory) value for X, a dual click on the slider goes back to this value
currentXnumberfactoryXCurrent displayed X value
minYnumber0Minimal value for Y
maxYnumber0Maximal value for Y
stepYnumber1Step between two consecutive Y possible values. e.g. 1 for a value from 0 to 127, 0.01 for fine adjustement of object position in the score... The bigger the faster mouse wheel and keyboard will change the value.
factoryYnumbercurrentYDefault (factory) value for Y, a dual click on the slider goes back to this value
currentYnumberfactoryYCurrent displayed Y value
displayValuesMaskstring"%x, %y"Mask for displaying values, %x and %y are replaced by values.
Returns
number: X, nil if user cancelled the dialog
number: Y, nil if user cancelled the dialog
Errors
if minX >= maxX or minY >= maxY
if factoryX or currentX are outside of [minX:maxX] range
if factoryY or currentY are outside of [minY:maxY] range
if factoryX and currentX, or factoryY and currentY are nil.
Example


 -- Create a new document with one staff, go to Page mode.
 -- This code moves first staff name position
 -- X between -50 and 50, Y between -30 and 30, steps are 1
 -- Negative Y go up, positive Y go down.
 -- Factory position is 0,0, current is 5,-24
   Include "SMUtils"
   x,y = EnterXY("Test XY",
    -50, 50, 1, 0, 5,
    -30, 30, 1, 0, -24,
    false, true, {FrontScore()},
    function(x,y,args)
      local staff = args[1].FirstStaff
      staff.TitleXOffset, staff.TitleYOffset = x, y
      Application.UpdateScores()
    end,
    "%x px, %y px" -- not mandatory, just show that unit is pixel (in 72 DPI)
  )

ChooseNoteHeadShape(int defaultValue)

Open a dialog to choose a note head shape.

ParameterTypeDefaultDescription
defaultValueintSHAPE_NORMALOne of SHAPE_* constants in MSDefine
Return
int: One of SHAPE_* constants, or nil if user cancelled the choice.

EnsureObjectInStaffArea(Score score, Staff staff, obj)

Ensure an object is in the Staff area, move it vertically if needed.

ParameterTypeDefaultDescription
scoreScore score
staffStaff staff
obj  Object: Dynamic, StaffText, FXProcessor, Picture
Return
boolean: true if object has been moved vertically, false otherwise.

CopyOrnaments(Symbol from, Symbol to)

Copy all ornaments from a Symbol to another one.

ParameterTypeDefaultDescription
fromSymbol The source symbol
toSymbol The destination symbol
Returns
int: Number of copied ornaments
int: Number of copy errors

IsThemeSoundsActive()

Are interface sounds active in scripts using SMDialog and SMMenu?

To set up screen reader, go to Scripts > Miscellaneous > Swiss knife menu, then Settings > Interface sounds.

Return
boolean: true if active, nil or false if not set up.

PlayThemeSound(string soundName, boolean wait)

Play a "theme" sound, if set to active.

ParameterTypeDefaultDescription
soundNamestring One of "open", "close", "bell", "error", "confirmation", "message", "toggle-off", "toggle-on", "window-slide"
waitbooleanfalseIf true, wait until sound file if played to continue script execution. If false, script continue immediately. A new call to PlayThemeSound(...) or Application.PlayWavFile(...) may interrupt and replace the first played sound.

IsScreenReaderActive()

Is there a screen reader, a voice that assist visually impaired user?

The screen reader is set up by the script in Miscellaneous > Screen Reader setup. A call to ScreenReader("words to say") wil lsay nothing if not set up, or will say the words if a human voice is choosen.
If the words need time or resource to be build, you can optimize your code by calling IsScreenReaderActive() before this task.

To set up screen reader, go to Scripts > Miscellaneous > Swiss knife menu, then Settings > Accessibility.

Return
boolean: true if active, nil or false if not set up.
See
ScreenReader

MuteScreenReader(int delay)

Temporarily mute the Screen Reader for a short delay.

It may be useful, for optimization concerns, if next coming actions will call ScreenReader(...) multiple times in a very short delay.
If ScreenReader is not set up to active, then this has no effect.

ParameterTypeDefaultDescription
delayint1000Delay, in milliseconds.
See
UnMuteScreenReader

UnMuteScreenReader()

After MuteScreenReader(...) and the massive actions that would have produced unaudible audio messages, unmute the Screen Reader.

If ScreenReader is not set up to active, then this has no effect.

See
MuteScreenReader

ScreenReader(string text, boolean wait)

Say the text if text to speech is enable for visually impaired people (screen reader).

ParameterTypeDefaultDescription
textstring text
waitbooleanfalseWait until the text is fully said

SMAlert(string msg)

Add accessibility to built-in Alert() function.

ParameterTypeDefaultDescription
msgstring msg

SMConfirmation(string msg)

Add accessibility to built-in Confirmation() function.

ParameterTypeDefaultDescription
msgstring msg
Return
boolean: The same result than Confirmation(msg)

SMMessage(string msg, boolean skipVisual)

Add accessibility to built-in Message() function.

The Message(...) display msg and requires user to click 'Ok' button or press Enter key. If a screen reader is set (Scripts > Misc. > Swiss knife menu > Settings), msg is said by the TTS. An optional argument allow only vocal message (skip the dialog) if screen reader is active.

ParameterTypeDefaultDescription
msgstring msg
skipVisualbooleanfalseIf screen reader is active, say msg but skip the Message(...) dialog. Visually impaired user will hear the message and won't need to click the 'Ok' button.

MenuSingleChoice(string title, Lexicon lexicon, datas, string header, boolean hideRadios)

Menu to pick one value in a list of items as radio buttons.

Single choice menu with radio buttons.

ParameterTypeDefaultDescription
titlestring Menu title
lexiconLexicon Lexicon for title and captions translation, nil for no translation.
datas  Can be a Map, a Collection or a table. Map keys are the values, map's value are string or table. Collection and table values are string or table.
table contents:
  1. string: the caption,
  2. Optional boolean: selected
  3. Optional: value, any kind of object, not necessary in a Map
  4. Optional string: left icon, "image:filename.ext" where filename.ext is in script directory or one of Harmony's install subdir, or "text:..." a short (styled or not) text
  5. Optional string: Keyboard shortcut
headerstring""Header question, more visible than window title. Can be styled, multiple lines
hideRadiosbooleanfalseBy default, radio buttons are displayed.
  • If false, selected choice is highlighted, keyboard/mouse selection of a button requires Enter or click on OK button.
  • If true selected choice is not highlighted, mouse a click or shortcut press the button and close the window.
Hiding radios may be seen as replacement of a Confirmation(...) where you need more answers than yes/no.
Return
choosen value (or caption), or nil if user canceled the choice.
See
https://www.myriad-online.com/cgi-bin/bbs/YaBB.pl?board=MYRSCRIPT;action=display;num=1760458849
Example


 local sd = MenuSingleChoice("Change stems direction", nil,
      {{"Auto", true, STEM_AUTO, "image:stemupdown.png"},
       {"Up", false, STEM_UP, "image:stemup.png"},
       {"Down", false, STEM_DOWN, "image:stemdown.png"}
      })
 if sd then -- change the stems direction of symbols
    -- sd = STEM_AUTO, or STEM_UP, or STEM_DOWN
 else -- sd=nil, no selection, user canceled the choice
 end

MenuMultipleChoice(string title, Lexicon lexicon, datas, int minNbOfChoice, int maxNbOfChoice, string header)

Menu to pick multiple value in a list of items as checkboxes.

For example, ChooseStaves(...) call it.

Multiple choice menu with checkboxes.

ParameterTypeDefaultDescription
titlestring Menu title
lexiconLexicon Lexicon for title and captions translation, nil for no translation.
datas  Can be a Map, a Collection or a table. Map keys are the values, map's value are string or table. Collection and table values are string or table.
table contents:
  1. string: the caption,
  2. Optional boolean: selected
  3. Optional: value, any kind of object, not necessary in a Map
  4. Optional string: left icon, "image:filename.ext" where filename.ext is in script directory or one of Harmony's install subdir, or "text:..." a short (styled or not) text
  5. Optional string: Keyboard shortcut
minNbOfChoiceint1Minimum number of items to choose, 0 means user can select nothing.
maxNbOfChoiceint0Maximum number of items to choose, 0 means no limit.
headerstring""Header question, more visible than window title. Can be styled, multiple lines
Return
table: Choosen values (or captions), or nil if user canceled the choice.

ChooseStaves(Score score, boolean multiple, boolean visibleOnly, function filterFunc, function selectFunc, int minNbOfChoice, int maxNbOfChoice)

Ask the user to choose one or multiple staves.

The builtin Score.UserChooseStaves(...) is a bit less flexible and not 100% browsable with keyboard. This custom version allow shortcuts, from 1 to 9 for 9 first staves, then the first available letter.

Here is what it looks like:

ChooseStaves(...) displays a menu with checkboxes.

ParameterTypeDefaultDescription
scoreScore score
multiplebooleantruetrue if several staves can be chosen, false if only one staff can be chosen.
visibleOnlybooleantruetrue if only visible staves are provided.
filterFuncfunction Function that receives Score and Staff arguments, returns true if the staff appears in list, false if not.
selectFuncfunction Function that receives Score and Staff arguments, returns true if the staff is selected by default, false if not selected.
minNbOfChoiceint1Minimum number of staves to choose, 0 means user can choose no staff. No effect if multiple is false.
maxNbOfChoiceint0Maximum number of staves to choose, 0 means no limit. No effect if multiple is false.
Return
table: Table of choosen staves, can be empty, or nil if user canceled the choice.

GetStavesGroups(Score score, Staff staff)

Get all StavesGroups of the score or containing staff if this argument is provided.

ParameterTypeDefaultDescription
scoreScore score
staffStaffnilIf nil, return all StavesGroups of the score, else return the ones containing staff.
Return
table: An array of StavesGroups, ordered from first to last Staff (Score.FirstStavesGroup is the first created in the document, not the first printed). Array is empty if no StavesGroups found.
Error
if score is not a Score or staff is not a Staff

GetStavesInGroup(StavesGroup sg)

Return an array of staves in StavesGroup sg

ParameterTypeDefaultDescription
sgStavesGroup sg
Return
table: Array of Staff

GetMergedStaves(Staff staff)

Get all staves merged with staff, included.

If staff is not merged, it returns {staff}, 1, only the argument staff, and 1 is the index of it in the table.

ParameterTypeDefaultDescription
staffStaff staff
Returns
table: Table of Staff objects
int: The index of staff in the table.

StavesGroupName(StavesGroup sg)

Return the name (title) of sg or build a name from its first and last grouped staves.

ParameterTypeDefaultDescription
sgStavesGroup sg
Return
string: Unstyled string
Error
if sg is not a StavesGroup

ChooseStavesGroups(Score score, boolean multiple, boolean visibleOnly, function filterFunc, function selectFunc)

Ask the user to choose one or multiple staves groups.

ParameterTypeDefaultDescription
scoreScore score
multiplebooleantruetrue if several staves groups can be chosen, false if only one staves group can be chosen.
visibleOnlybooleantruetrue if only visible staves groups are provided.
filterFuncfunction Function that receives Score and StavesGroup arguments, returns true if the staves group appears in list, false if not.
selectFuncfunction Function that receives Score and StavesGroup arguments, returns true if the staves group is selected by default, false if not selected.
Return
table: Array of choosen staves groups, can be empty, or nil if user canceled the choice.

AdjustStavesGroupSymbolPosition(Score score, table groups)

Experimental: Adjust horizontal and vertical staves group symbole (braces and brackets).

ParameterTypeDefaultDescription
scoreScore score
groupstablenilTable of StavesGroup to modify, others are unchanged. nil or empty table means all staves group of score.
Return
int: Number of modified staves group symbols.

StaffSetAmbitus(Score score, Staff staff, boolean state)

Set the ambitus enabled or disabled for staff, and also at score's level else ambitus won't display.

ParameterTypeDefaultDescription
scoreScore score
staffStaff staff
stateboolean true to show ambitus, false to hide it.

ChooseView(Score score, boolean index, int (default=current)

Ask the user to choose one view, or a value for ViewIndex.

ParameterTypeDefaultDescription
scoreScore score
indexboolean Add the choices
  • 0 = all views
  • -1 = general view
  • -2 = all views including staff
  • -3 = all views except general view
(default=currentint view) selected index
Return
int: view index

FontFaceNumberToString(int face)

Convert a font face (sum of FACE_* constants from MSDefine) to strings.

ParameterTypeDefaultDescription
faceint face
Returns
string: Long format string in English, e.g. "Bold, Italic"
string: Short format string, usable as well as number in SetStringStyle(...), e.g. "BI", but works better.
"" for no style (standard)

FontFaceStringToNumber(string str)

Convert a font face as string like "BI" into sum of FACE_* constants from MSDefine.

ParameterTypeDefaultDescription
strstring Chars B,I,U,O,S,C,E are converted, others are ignored
Return
int: Sum of FACE_* constants

ChooseFont(string object, table suggestedFonts, selected)

Ask the user to choose one font in a menu.

Choose tempo font menu
If available, the list starts by the font set in global settings > Fonts for object (e.g. "Tempo", "Staff name", see GetPreferredFont(..)),
then, a list of favorites fonts,
then, a list of suggested fonts (e.g. found in score).

ParameterTypeDefaultDescription
objectstring One of the items in the global settings dialog in English: "Staff name", "Break text", "Tempo", "Rules names", "Effects & ornaments", "Tablature key", "Tablature grace note", "Tablature note", "Chord grid name", "Chord grid display", "Chord grid summary", "Key summary", "Karaoke line", "Ruler", "Help window", "Array", "Pop up menus"
or another object of your choice such as "Lyrics".
suggestedFontstable A table of TextStyle or table {name, face, size[, color]}
selected  A TextStyle or table {name, face, size[, color]}
Returns
string: Font name, nil if user canceled the choice.
int: Font face, sum of FACE_* constants in MSDefine
int: Size
string: RGB color

EnterFont(string font, face, number size, string color)

Ask the user to choose font, face, size and color using the built-in EditTextStyle() dialog.

EnterFont(...) calls EditTextStyle(...)
Returns TextStyle properties instead of TextStyle object itself, as it is mandatory to dispose it, and often forgotten.

ParameterTypeDefaultDescription
fontstringnilDefault font
face nilDefault face. A number (sum of FACE_* constants) or a string like "BI" for bold italic, second returned value by FontFaceNumberToString(...).
sizenumbernilDefault size
colorstringnilDefault color in RGB format.
Returns
string: Font name, nil if user canceled the choice.
int: Font face, sum of FACE_* constants in MSDefine
int: Size
string: RGB color

ChooseColor(string object, table suggestedColors, selected)

Ask the user to choose one color in a menu.

Choose staff line color, there are 5 favorites
If available, the list starts by a list of favorites colors, saved by previous choices for the same object (e.g. "Staff background").
Then, a list of suggested colors (e.g. found in score).
Then, the ability to pick a new color from the Color Picker, and save it to favorites for faster use next times.

ParameterTypeDefaultDescription
objectstring The name you want, e.g. "Staff background", "Staff lines"...
suggestedColorstablenilA table of string in [#]RRGGBB format (recommanded), or number color index
selected  A string in [#]RRGGBB format or number color index
Returns
string: Choosen color, in RRGGBB format, or nil if user canceled the choice.
string: Choosen color, in #RRGGBB format, or nil if user canceled the choice.
int: Color index, or nearest in 256 colors palette, or nil if user canceled the choice.

AddImagesDirectory(string path)

Add a directory where script can search for pictures.

Menus and other Component may include image (picture) which are searched by file name in some Harmony's subdirs, but not in relative paths from the current script. If you script embed images, it is good practice to call AddImagesDirectory(GetCurrentScript()) just after Include "SMUtils".

ParameterTypeDefaultDescription
pathstring path

IsPowerOfTwo(number n)

Is n a number power of 2?

ParameterTypeDefaultDescription
nnumber n
Return
boolean: true if n equals 1, 2, 4, 8, 16..., nil (for false) if not.
Error
if n is not a number

flag_test(number set, number flag)

Test if a bit is set, the bit can be seen as a flag.

ParameterTypeDefaultDescription
setnumber A sum of flags
flagnumber The big to test, a number power of 2.
Return
boolean: true if flag is already set, nil (for false) if not.
Error
if set is not a number or if flag is not a power of 2.
Example


   Include "SMUtils"
   local face = FACE_ITALIC + FACE_BOLD
   local x = flag_test(face, FACE_UNDERLINE) --> x = nil (false)
   x = flag_test(face, FACE_BOLD) --> x = true

flag_set(number set, number flag)

Set a bit to 1, the bit can be seen as a flag.

ParameterTypeDefaultDescription
setnumber A sum of flags
flagnumber The big to set to 1, a number power of 2.
Return
number: The new value for set
Error
if set is not a number or if flag is not a power of 2.
Example


   Include "SMUtils"
   local face = FACE_ITALIC + FACE_BOLD
   face = flag_set(face, FACE_BOLD) --> face is unchanged, already set
   face = flag_set(face, FACE_UNDERLINE) --> face equals italic+bold+underline

flag_clear(number set, number flag)

Clear a bit to 0, the bit can be seen as a flag.

ParameterTypeDefaultDescription
setnumber A sum of flags
flagnumber The big to clear, a number power of 2.
Return
number: The new value for set
Error
if set is not a number or if flag is not a power of 2.
Example


   Include "SMUtils"
   local face = FACE_ITALIC + FACE_BOLD
   face = flag_clear(face, FACE_UNDERLINE) --> unchanged, underline not set
   face = flag_clear(face, FACE_BOLD) --> face now equals FACE_ITALIC

table_insert_multi(table t, ...)

Insert multiple items in a table in one call.

ParameterTypeDefaultDescription
ttable t
...  Undefined number of arguments

JumpAndSelectBar(Score score, int barN, Staff staffBegin, Staff stafEnd)

Jump to the requested bar number and select it, all staves or the requested staff if not nil.

Try to position the selected bar near the center of the screen, unlike Score.JumpToBar(...) which also doesn't select.

ParameterTypeDefaultDescription
scoreScore score
barNint Bar number, must be lower or equal to Score.NumberOfBars
staffBeginStaffnilIf not nil, first or only staff to select, instead of all staves.
stafEndStaffnilIf not nil, last staff to select
Error
if barN > score.NumberOfBars or staff is not nil and not a Staff.

SaveScoreAppearance(Score score, string setName, boolean full)

Save score appearance settings in a file.

Harmony Assistant only allow to save one default set, but you may need several sets, for solo parts, for conductor...

ParameterTypeDefaultDescription
scoreScore score
setNamestring Setting name, e.g. "conductor", "drums"
fullboolean true to save all settings, false to save only those that differs from factory settings.

LoadScoreAppearance(Score score, string setName)

Load score appearance settings from a file saved by SaveScoreAppearance(...).

Harmony Assistant only allow to save one default set, but you may need several sets, for solo parts, for conductor...
Only the settings read from the file are modified, missing settings are untouched.

ParameterTypeDefaultDescription
scoreScore score
setNamestring Setting name, e.g. "conductor", "drums"
Return
int: Number of modified settings

CopyFreeObjects(Score src, Score dest)

Copy free objects from one Score to another.

FreeObject visible only on a specific view are copied to the view with the same name, else to all views.
All properties, including tags, are copied.

ParameterTypeDefaultDescription
srcScore src
destScore dest
Return
int: Number of copied free objects

BatchStartRecording(string batchName)

Just set a flag that tells we are currently recording and stacking functions for further batch processing.

ParameterTypeDefaultDescription
batchNamestring Batch name, by convention the type of object function will accept as argument ("Score", "Staff"...).

BatchStopRecording(string batchName)

Cancel the flag that tells we are recording and stacking operations for batch processing, without clearing the stack.

ParameterTypeDefaultDescription
batchNamestring Batch name, by convention the type of object function will accept as argument ("Score", "Staff"...).
Return
int Stack size

BatchIsRecording(string batchName)

Is the batch currently stacking?

If yes, then function must be stacked by BatchAdd, else performed directly.

ParameterTypeDefaultDescription
batchNamestring Batch name, by convention the type of object function will accept as argument ("Score", "Staff"...).
Return
bvool true if recording, nil (for false) if not
Example


     if BatchIsRecording("Score") == true then
      BatchAdd("Score", "My action", MyFunction)
    else
      MyFunction(FrontScore())
    end

BatchAdd(string batchName, string label, function func)

Stack a function for batch processing.

ParameterTypeDefaultDescription
batchNamestring Batch name, by convention the type of object function will accept as argument ("Score", "Staff"...).
labelstring Just a label to show progression or report an error with context.
funcfunction The function that will be performed later, by BatchExecute.
  • If batchName is a conventional objet type ("Score", "Instrument"...) then the first argument must be of that type.
  • In most cases, a Score object is given as a second argument, the function can ignore it.
  • No return value is expected. In case of error, call throw("Error message", true), true means visual alert, false console only.

BatchClear(string batchName)

Clear the batch stack, in case of cancellation or when all calls are done.

ParameterTypeDefaultDescription
batchNamestring Batch name, by convention the type of object function will accept as argument ("Score", "Staff"...).

BatchExecute(string batchName, Score score, object)

Execute the batch function stack on the objects in argument table.

ParameterTypeDefaultDescription
batchNamestring Batch name, by convention the type of object function will accept as argument ("Score", "Staff"...).
scoreScore If needed, the score on which the batch will be processed
object nilThe object (Staff, Instrument...) that will be given as first argument to each function in the stack.
Return
int: Number of functions called.

DeleteDisabledCurves(Staff staff)

Remove the parameter curves that have been disabled.

ParameterTypeDefaultDescription
staffStaff staff
Return
int: Number of deleted curves

DeleteEmptyCurves(Staff staff)

Remove the empty parameter curves when they have no values.

ParameterTypeDefaultDescription
staffStaff staff
Return
int: Number of deleted curves

InsertReservedPages(Score score)

Insert reserved pages, after the already existing if any) and shift the free objects to next pages.

e.g.: A free object is on page 2 of a score without any reserved pages, after insertion of 1 reserved page, the free object will move to page 3.

ParameterTypeDefaultDescription
scoreScore score

DeleteReservedPages(Score score)

Delete reserved pages from a score, if any, and move or delete the free objects visible on the reserved pages.

  • A free object is on the 2nd page of the score, but page 3 as the score has 1 reserved page: the object will move to page 2 to stay on 2nd score page.
  • Free objects visible only on reserved pages are deleted.

ParameterTypeDefaultDescription
scoreScore score

Serialize(obj)

Serialize an object to store it as string and later deserialization.

ParameterTypeDefaultDescription
obj  A number, string, table or a class that own :serialize(...) method.
Return
string: string
Error
If something can't be serialized.

Deserialize(string str)

Deserialize a string into object.

ParameterTypeDefaultDescription
strstring str
Return
Copy of previously serialized object

StorageAreaClear(StorageArea storage, string tag4)

Remove all items from the StorageArea storage for tag tag4.

ParameterTypeDefaultDescription
storageStorageArea Application.StorageArea, myScore.StorageArea...
tag4string 4-char tag
Return
int: Number of deleted items

DeleteAllFreeObjects(Score score)

Delete all free objects from a score, without confirmation.

ParameterTypeDefaultDescription
scoreScore score
Return
int: Number of deleted free objects

DeleteHiddenFreeObjects(Score score)

Delete all hidden free objects from a score, without confirmation.

A free object is hidden when "Don't print" is checked."

ParameterTypeDefaultDescription
scoreScore score
Return
int: Number of deleted free objects

ChooseTarget(Score score, string prompt, int selectedBar, string selectedName)

Select a Target (rehearsal mark) in the Score.

ParameterTypeDefaultDescription
scoreScore score
promptstring"Select a rehearsal mark"Title of the menu.
selectedBarint0Preselect target from the bar number selectedBar:
  • negative means no pre-selection,
  • nil or 0 means current cursor position (Score.TimeBeginSelection),
  • Positive number pre-selects the target where Target.Bar <= selectedBar.
selectedNamestringnilSelect the target which displayed name is selectedName. nil means no selection from the target displayed name.
Return
Target: Selected target or nil if user canceled the choice.

TargetVisibility(Score score, Target target, boolean visible)

Turn one or all targets visible or hidden.

The property for visibility Target.DisplayCaption is an inverted boolean. This function makes your code more comprehensible, and if inversion is fixed in a future version, you won't have to modify your code.
This doesn't regenerate captions nor refresh the score on screen.

ParameterTypeDefaultDescription
scoreScore score
targetTargetnilnil for all targets of score
visibleboolean visible
Return
int: Number of modified targets

TargetSplitMultiRests(Score score)

Split multi-rests at all visible rehearsal marks, for all views.

The property is set to the previous bar.

ParameterTypeDefaultDescription
scoreScore score

TargetHideBarNumbers(Score score)

Hide bar numbers at bar that display a rehearsal mark, for all views.

Common practice in orchestral score, rehearsal marks are framed big bar numbers, so no need to display regular bar numbers at these bars.

ParameterTypeDefaultDescription
scoreScore score

DeleteUselessClefs(Staff staff)

Delete useless clef change that are visible clefs with no changes.

After PDF or MusicXML import, you may find clefs on every lines, displayed in scroll mode. Harmony doesn't need such bar settings, there is a print option that repeats clefs on every line.

ParameterTypeDefaultDescription
staffStaff staff
Return
int: Number of deleted clefs.

ShowHiddenClefs(Staff staff)

Show hidden clefs where needed.

After PDF or MusicXML import, if a staff is invisible on first page, first clef is hidden.

ParameterTypeDefaultDescription
staffStaff staff
Return
int: Number of shown clefs.

MidiGetEventFiltered(boolean allowNoteOn, boolean allowNoteOff, boolean allowCC, boolean allowProgramChange, boolean allowAftertouch, boolean allowPitchBend, boolean allowOthers, int delay, table allowedSources)

Apply a filter to Midi.GetEvent to exclude some Midi messages and return all events since last call.

You can exclude:

  1. message you don't need, e.g. aftertouch
  2. a lot of steps while moving a controller (slider, knob, pitch bend).
    To do this, set a delay in milliseconds. This result in a loss of data, note suitable for fine control of sound, but useful when hardware controllers replace mouse or computer keyboard inputs.

ParameterTypeDefaultDescription
allowNoteOnbooleantrueAllow Note On events?
allowNoteOffbooleantrueAllow Note Off events?
allowCCbooleantrueAllow controller change events?
allowProgramChangebooleantrueAllow PC event?
allowAftertouchbooleantrueAllow aftertouch event?
allowPitchBendbooleantrueAllow pitch bend event?
allowOthersbooleantrueAllow other events?
delayint0Delay in milliseconds for CC and pitch bend, reduce the number of events returned while the wheel or controller is sliding / rotating.
If delay is set, then only the last value is returned.
allowedSourcestablenilThe accepted sources (nil means all - no filter):
  • INPUT_SOURCE_UNKNOWN: none/unknown
  • INPUT_SOURCE_MIDI: from an external MIDI device
  • INPUT_SOURCE_VIRTUAL_KBD: from a click on a virtual keyboard
  • INPUT_SOURCE_COMPUTER_KBD: from the computer keyboard
  • INPUT_SOURCE_PLAYED_MUSIC: from the played score
Return
table: Table of Midi events, each item are structured as:
  • Event, int: type of event :
    • 1 mean note on (key pressed),
    • 2 mean note off or note on with velocity = 0 (key released)
    • 10 means polyphonic aftertouch
    • 11 means CC, Controller Change (modulation wheel, pedal, knobs, cursors, bank change...)
    • 12 means PC, Program Change
    • 13 means channel aftertouch
    • 14 means pitch bend
  • Channel, int: the channel from 0 to 15
  • Pitch, int: the note pitch / selected controller / program from 0 to 127
  • Velocity, int: the velocity / controller value from 0 to 127
  • TimeMs, int: the time position in millisecond of the event
  • TimePos, number: the time position in the playing score (-1 if no score currently playing)
  • Source, int: the source for this event (MSDefine constant):
    • INPUT_SOURCE_UNKNOWN: none/unknown
    • INPUT_SOURCE_MIDI: from an external MIDI device
    • INPUT_SOURCE_VIRTUAL_KBD: from a click on a virtual keyboard
    • INPUT_SOURCE_COMPUTER_KBD: from the computer keyboard
    • INPUT_SOURCE_PLAYED_MUSIC: from the played score

MidiSendCC(int interface, int channel, int controller, int value)

Send a control change (CC) message to a MIDI device.

ParameterTypeDefaultDescription
interfaceint 1-based to match the numbering in hardware configuration (1-12)
channelint 1-based to match the usual chanel numbering (1-16)
controllerint 0 for bank select, 1 for modulation wheel, 2 for breath control...
See https://anotherproducer.com/online-tools-for-musicians/midi-cc-list/
valueint between 0 and 127
Example


 function findTeensy()
  for i=1,12 do
    local name = Midi.OutGetName(i)
    if name == "Teensy MIDI" then return i; end
  end
 end
 Midi.OutBegin("Teensy MIDI")
 MidiSendCC(port, 1, 90, 50)
 Midi.OutEnd()

ElementsToTable(...)

Transforme a list (multiple returned values from a function call) to a table.

ParameterTypeDefaultDescription
...  List of elements
Return
table: Table containing all elements.
See
TableToElements
Examples


 print(strfind("abcd", "b", 1, true)) --> 2 2
 local pos = strfind("abcd", "b", 1, true) --> 2, one data lost
 local t = ElementsToTable(strfind("abcd", "b", 1, true)) --> {2, 2}


 -- Symbol.GetSlurSettings returns variable number of vallues,
 -- symbol.SetSlurSettings accept variable number of arguments
 -- Here is a "hack" to change slur settings safely.
 local ss = ElementsToTable(symbol.GetSlurSettings())
 ss[1] = SLIDE_SMOOTH
 ss[12] = true -- automatic computing
 symbol.SetSlurSettings(TableToElements(ss))

TableToElements(table t)

Bugfix version of MSLibrary's PushAllTableElts(t), return all elements of a table as multiple return values.

PushAllTableElts(...) doesn't hnandle string nor complex objects, this version does.

ParameterTypeDefaultDescription
ttable If table is indexed as t = {1, "b", 3} then values are returned in their order. Else if table is made of pairs variable to value like in t = {A=1, B="b", C=3} order is not guaranteed.
Return
All values of the table
Error
if not enough free stack / too big table
See
ElementsToTable
Examples


 local t = {1, "b", 3, FrontScore()}
 print(TableToElements(t)) --> 1 b 3 userdata(...)
 -- PushAllTableElts(t) returns 1 nil 3 and crashes


 -- Symbol.GetSlurSettings returns variable number of vallues,
 -- symbol.SetSlurSettings accept variable number of arguments
 -- Here is a "hack" to change slur settings safely.
 local ss = ElementsToTable(symbol.GetSlurSettings())
 ss[1] = SLIDE_SMOOTH
 ss[12] = true -- automatic computing
 symbol.SetSlurSettings(TableToElements(ss))

CopyBarNumberings(Staff source, Staff dest)

Copy bar numberings settings from one staff to another.

ParameterTypeDefaultDescription
sourceStaff source
destStaff dest

GetBarVisibilityState(Score score, int firstBar, int lastBar)

Get the visibility state of all bars between firstBar and lastBar.

Bars can be invisible if out of print region, in the middle or at the end of a multi-rest.

ParameterTypeDefaultDescription
scoreScore score
firstBarint1 
lastBarintscore.NumberOfBars 
Return
table: A table of bar number to int value:
  • BAR_STATE_VISIBLE: normal bar, visible,
  • BAR_STATE_MULTI_FIRST: visible, first bar of a multi-rest or multi-repeat,
  • BAR_STATE_MULTI_MIDDLE: not visible, inside (but not last bar of) a multi-rest or multi-repeat,
  • BAR_STATE_MULTI_LAST: not visible, last bar of a multi-rest or multi-repeat,
  • BAR_STATE_BEFORE_PRINT_REGION: not visible, before first printed bar,
  • BAR_STATE_AFTER_PRINT_REGION: not visible, after last printed bar,
  • BAR_STATE_UNDEFINED: should never happen because calculation is made by switching to Page mode if necessary.
Example


 local first,last = 10,35
 local bsv = GetBarVisibilityState(FrontScore(), first, last)
 for i=first,last do
    if bsv[i] == BAR_STATE_MULTI_LAST then
      -- set force display bar number after a multi-rest
      FrontScore().GetGlobalBarSetting(i+1).IsForcedDisplay = true
    end
    FrontScore().Update()
 end

DontSplitTwoAndFourRepeats(Score score, int firstBar, int lastBar)

In current view, avoid split (end of line) in the middle of %2 and %4 bar-repeats.

Set global bar settings : DontBreakLine = true, EndOfLine = false, EndOfPage = false.

ParameterTypeDefaultDescription
scoreScore score
firstBarint1First bar where %2 and %4 are searched
lastBarintscore.NumberOfBarsLast bar where %2 and %4 are searched
Return
int: Number of modified bars

SetGhostRestDisplayMode(Score score, int grdm)

Set the ghost rest display mode for all staves in all views.

ParameterTypeDefaultDescription
scoreScore score
grdmint 
  • 0 = don't display
  • 1 = display with a mark
  • 2 = display whole rest in empty bars
  • 3 = display with real rests

bin2int(string s, boolean signed)

Converts binary number (string containing only "0" and "1") to number.

Shortcut to tonumber(s, 2) with protection and no 32-bit limit

ParameterTypeDefaultDescription
sstring s
signedbooleanfalseSigned or unsigned integer?
Return
int: 0 or positive integer
Error
if s is not a binary string

hex2int(string s, boolean signed)

Converts hexadecimal number (string containing 0-9a-fA-f) to number.

Shortcut to tonumber(s, 16) with protection and no 32-bit limit.

ParameterTypeDefaultDescription
sstring s
signedbooleanfalseSigned or unsigned integer?
Return
int: 0 or positive integer
Error
if s is not an hexadecimal string

tohex(int n, int size, string separator)

Converts a number to hexadecimal string Shortcut to format("%x", n) with more options and no 32-bit limit

ParameterTypeDefaultDescription
nint Positive, 0 or negative.
sizeint1Pad result with zeros to ensure result string length is a multiple of size
separatorstring""Separate groups of size hex chars?
Return
string: string
Error
if n is not a number or size < 1 or separator is not a string.

tobin(int n, int size, string separator)

Converts a number to a binary string (containing only 0 and 1)

ParameterTypeDefaultDescription
nint n
sizeint1Pad result with zeros to ensure result string length is a multiple of size
separatorstring""Separate groups of size binary chars?
Return
string: string
Error
if n is not a number or size < 1 or separator is not a string.

BinNot(int a, int bits)

NOT bitwise operation MyrScript comes with BinAnd(...), BinOr(...), BinXor(...), BinShl(...), BinShr(...) but not the NOT bitwise operation.

Here it is!

ParameterTypeDefaultDescription
aint a
bitsint32 
Return
int: int
Example


 local a = 5 -- 0101
 print(bit_not(a, 4)) --> 10 (1010)

SMFirstSelectedSymbol(Score score, Staff staff, boolean ignoreGhostRest)

Returns the first selected symbol (range or individual selection) of the staff or the whole score.

This function is more accurate than Staff.FirstSelectedSymbol, handles individual selection, and the 3rd argument allows you to ignore ghost rests.

Note: like Staff.FirstSelectedSymbol, the returned symbol may not be included in actions applied to selection (in Edit menu). If the range selection is after the note head but before next note, it is considered as selected by MyrScript, whereas actions in Edit menu won't apply to it.

ParameterTypeDefaultDescription
scoreScore score
staffStaff If nil, look for selected symbol on all staves and return the one that begins the first (least symbol.Time)
ignoreGhostRestboolean If first selected symbol is a ghost rest, go forward until another kind of symbol is found
Return
Symbol: or nil if selection contains no symbol

SMLastSelectedSymbol(Score score, Staff staff, boolean ignoreGhostRest)

Returns the last selected symbol (range or individual selection) of the staff or the whole score.

This function is more accurate than Staff.LastSelectedSymbol, handles individual selection, and the 3rd argument allows you to ignore ghost rests.

Note: like Staff.LastSelectedSymbol, the returned symbol may not be included in actions applied to selection (in Edit menu). If the range selection is after the note head but before next note, it is considered as selected by MyrScript, whereas actions in Edit menu won't apply to it.

ParameterTypeDefaultDescription
scoreScore score
staffStaff If nil, look for selected symbol on all staves and return the one that ends the last (greatest symbol.Time + symbol.Duration)
ignoreGhostRestboolean If last selected symbol is a ghost rest, go backward until another kind of symbol is found
Return
Symbol: or nil if selection contains no symbol

SearchNextSymbol(Score score, staves, from, function matcher)

Search next symbol with custom matcher function, in whole score or a list of staves, at a time position or after a symbol.

ParameterTypeDefaultDescription
scoreScore score
staves nil
  • nil means all staves (whole score)
  • a Staff object to search in this staff only
  • a table of Staff objects to search in multiple staves
from 0
  • A int for a time, the result may be the symbol at this position
  • a Symbol to start search from this symbol, result is never this symbol
matcherfunctionnilA function that accepts a Symbol argument and returns true if the symbol matches the criteria(s) of the search. If matcher is nil then return the next symbol which is not a ghost rest.
Returns
Symbol: First matching symbol at time from or after from symbol, nil if not found (end of music is reached)
Staff: The staff containing the returned symbol, or nil if not found
Example


 local m = function(sym) return sym.IsRest; end
 local rest, staff = SearchNextSymbol(FrontScore(), nil, 0, m)
 local cpt = 0
 while rest do
   cpt = cpt + 1
   print("#"..cpt, "staff #"..staff.Index, "time="..rest.Time)
   rest, staff = SearchNextSymbol(FrontScore(), nil, rest, m)
 end

SearchPreviousSymbol(Score score, staves, from, function matcher)

Search previous symbol with custom matcher function, in whole score or a list of staves, at a time position or before a symbol.

ParameterTypeDefaultDescription
scoreScore score
staves nil
  • nil means all staves (whole score)
  • a Staff object to search in this staff only
  • a table of Staff objects to search in multiple staves
from music duration
  • A int for a time, the result may be the symbol at this position
  • a Symbol to start search from this symbol, result is never this symbol
matcherfunctionnilA function that accepts a Symbol argument and returns true if the symbol matches the criteria(s) of the search. If matcher is nil then return the previous symbol which is not a ghost rest.
Returns
Symbol: First matching symbol at time from or before from symbol, nil if not found (start of music is reached)
Staff: The staff containing the returned symbol, or nil if not found
Example


 local m = function(sym) return sym.IsRest; end
 local rest, staff = SearchPreviousSymbol(FrontScore(), nil, nil, m)
 local cpt = 0
 while rest do
   cpt = cpt + 1
   print("#"..cpt, "staff #"..staff.Index, "time="..rest.Time)
   rest, staff = SearchPreviousSymbol(FrontScore(), nil, rest, m)
 end

GetKeySignatureAtBar(Staff staff, int barN, boolean visibleOnly)

Get the key signature at requested bar of requested staff.

Search for last BarSetting less or equal to barN and retrieve its KeySignature. If visibleOnly is true then go backward until a visible key signature is found.

ParameterTypeDefaultDescription
staffStaff staff
barNint barN
visibleOnlybooleanfalseIf true, retrieve the last visible key signature. Else it can retrieve a hidden key signature.
Return
KeySignature: nil possible if no visible key signature and visibleOnly is true.

longest_common_subsequence(a, b)

Longest Common Subsequence (LCS) algorithm, basis for data comparison.

This compares 2 strings or tables (of numbers or strings) and returns a string or a table containing common chars or items.
For the two strings "ABC" and "ACE", the LCS is "AC".

ParameterTypeDefaultDescription
a  First string or table (of comparable elements)
b  Second string or table (of comparable elements)
Return
A string if a and b are strings, else a table.
Error
if type(a) ~= type(b)
See
CompareTextFiles
CompareTables
CompareStrings
https://en.wikipedia.org/wiki/Longest_common_subsequence
https://www.geeksforgeeks.org/dsa/longest-common-subsequence-dp-4/

CompareTables(table lines1, table lines2)

Compare two tables, returns a diff-like format.

The diff format is used for data comparison, or, in development environnement, to compare old and new lines of source code.

tables in arguments must contain comparable (==) and tostring()able items: so it's restricted to numbers and strings. For complex datas, consider serialization.

ParameterTypeDefaultDescription
lines1table First (oldest) table of strings
lines2table Second (newest) table of strings
Returns
table: Lines in approximate diff format:
  • Added lines start with a + (plus)
  • Removed lines start with a - (minus)
  • Common lines (unchanged) start with a space.
int: Number of added lines
int: Number of removed lines
int: Number of unchanged lines
See
CompareTextFiles
CompareStrings

table_unique(table tab)

Remove duplicates from a table

ParameterTypeDefaultDescription
tabtable tab
Return
table: table

RecentScriptsAdd(string path, string name)

In debug mode, add current script to the "Recent scripts" list.

This is a tool for devs that allow them to quickly run or edit most recents scripts, from Scripts > Miscellaneous > Dev tools > Recents scripts

ParameterTypeDefaultDescription
pathstringGetCurrentPath() Directory where the script is stored
namestringApplication.CurrentScriptNameScript file name
Usage

-- At the beginning of your script
 Include "SMUtils"
 RecentScriptsAdd()
 -- Run at least once your script from the editor (in debug mode)

SymbolGetAccidental(Symbol sym)

Return accidental data for a Symbol, handles microtonals.

Return nil if sym is not a note.

ParameterTypeDefaultDescription
symSymbol sym
Returns
int: Accidental constant from MSDefine (except AUTO). If the value is greater or equal than 1000, it is a microtonal accidental, see ORNAMENT_MA_* constants.
int: Accidental value in 100th of semitone.
boolean: true if accidental is visible, false if invisible
boolean: true if accidental is cautionary, false if essential. This may be true even if invisible, meaning that deleting this accidental will not change the note pitch.
string: Source of the accidental: "note", "bar" (previous note in the bar), "key" (key signature).

SymbolSetAccidentalVisibility(Symbol sym, boolean visible)

Change the accidental visibility of a Symbol.

Handles microtonal accidentals.

ParameterTypeDefaultDescription
symSymbol sym
visibleboolean true to display accidental, false to hide or delete
Return
boolean: true if changes were applied, false if not, nil if sym is not a note.

SymbolIsMicrotonalAccidental(Symbol sym)

Is the note played with a microtonal accidental?

ParameterTypeDefaultDescription
symSymbol sym
Return
boolean: true if sym or a previous note in the same bar has one Ornament of a microtonal accidental, or if the last specify a microtonal accidental for that note.

SymbolIsTieVisible(Symbol note)

Is the note tied?

A tie is a kind of "slur" joining two notes head. In Harmony, it is considered as a single note with a split duration.
Two rests may be "tied", without curve, this function ignore rests.

ParameterTypeDefaultDescription
noteSymbol note
Return
boolean: true if note is tied with next note.
See
Symbol Symbol.GetTiedElements(...)

SymbolsAreContiguous(Symbol a, Symbol b)

Tell if two Symbols are contiguous.

Both can be in chord, this can produce a.Next ~= b.
If both are quarters, and while a is played, 2 eights are also played, then b is considered as contiguous. If both have same pitch, a and b can be tied..
Another way to say: a.Time + a.Duration == b.Time and both are on the same staff.

ParameterTypeDefaultDescription
aSymbol a
bSymbol b
Return
boolean: true if a and b are contiguous
See
SymbolsCanBeTied

SymbolsCanBeTied(Symbol ...)

Symbols can be tied if they are all contiguous and have same played and displayed pitch.

ParameterTypeDefaultDescription
...Symbol A table of Symbols or multiple Symbol arguments. They must be ordered by their time, from first to last.
Return
boolean: true if a tie can join ALL notes in argument

SetSlurDirection(Symbol note, boolean isUp)

Set slur direction up or down.

The slur is set to be adjusted automatically.

ParameterTypeDefaultDescription
noteSymbol The note that starts the slur (the SlurSource). If it ends a slur and doesn't start another one, then the slur settings are set to source note. To avoid confusion, prefer passing the source note as argument.
isUpboolean true for up, false for down
Return
boolean: true if the slur has been modified

SymbolIsDotted(Symbol sym)

Tell if the Symbol is displayed with dot(s).

If sym is tied (sym.SplitDuration ~= 0), then returns true if at least one of the tied notes is dotted.
-- If sym has a slur instead of a tie, only sym is checked, as the slur target is another Symbol.

ParameterTypeDefaultDescription
symSymbol sym
Return
boolean: true if sym requires dot(s) to display its duration on the score.

GetSymbolsInChord(Symbol sym)

Return all symbols in chord with sym (included), in its staff and merged ones.

Symbols are sorted by staff index, then their internal order (generally from higher to lower). This is not guaranteed that symbols are all ordered from higher to lower. Rests are included.

ParameterTypeDefaultDescription
symSymbol sym
Returns
table: Table of Symbol in chord with sym
int: Index of sym in the table.
See
GetOverlappingSymbols

GetOverlappingSymbols(Symbol sym)

Get all symbols (notes and rests) from merged staves, which begin time is before sym end time, and end time is after sym begin time.

This means: if sym is a "drone" note in first merged staff, this will return the drone + the melody in the second merged staff.

in this 2-voices staff with tied notes (no slurs), overlapping symbols of the blue one are the green one. The blue one is also returned, and the second returned value gives its index in the returned table.

If the drone is a serie of notes linked by a slur, then the function must be called for each note of the serie.
If all notes of the drone are tied, it's considered as only one note.

This function may help analysis algorithm, as well as for ties/slurs/stems direction calculation.

There is no guarantee of sorted results: it will be mostly sorted by staff index, time, higher to lower in chord.

ParameterTypeDefaultDescription
symSymbol sym
Returns
table: Table of Symbol which playing time and duration overlap sym playing time.
int: Index of sym in the table.
See
GetSymbolsInChord

CompareSymbolsByPitch(Symbol a, Symbol b)

Compare two Symbols by pitch, then displayed height.

ParameterTypeDefaultDescription
aSymbol a
bSymbol b
Return
int:
  • Negative number if a is lower than b,
  • Positive if a is higher than b,
  • Zero if a and b have same pitch and displayed height.

LinearScaling(number x, number a, number b, number c, number d)

Linear scaling (or linear transformation) of \(x\) from range \([a,b]\) to \([c,d]\).

Use case: convert a MIDI value between 0 and 127 to a number between 0% and 100%.

ParameterTypeDefaultDescription
xnumber x
anumber a
bnumber b
cnumber c
dnumber d
Return
number: \[ c + \frac{(d - c)(x - a)}{b - a} \]
Error
if \(a > b\), or \(c > d\), or \(x\) not in range \([a,b]\).

QuadraticScaling(number x, number a, number b, number c, number d)

Quadratic scaling of \(x\) from range \([a,b]\) to \([c,d]\).

Low values of \(x\) are compressed, high values are expanded.

Use case: a knob or cursor for reverb duration between 0 and 5 s. We need a more precise short duration (0.1 s, 0.3 s) than a longer one (no big difference between 4.5 s and 4.7 s).

ParameterTypeDefaultDescription
xnumber x
anumber a
bnumber b
cnumber c
dnumber d
Return
number: \[ c + (d - c) \left(\frac{x - a}{b - a}\right)^2 \]
Error
if \(a > b\), or \(c > d\), or \(x\) not in range \([a,b]\).
See
SquareRootScaling
PowerScaling

SquareRootScaling(number x, number a, number b, number c, number d)

Square root scaling of \(x\) from range \([a,b]\) to \([c,d]\).

Inverse of QuadraticScaling, high values of \(x\) are compressed, low values are expanded.

ParameterTypeDefaultDescription
xnumber x
anumber a
bnumber b
cnumber c
dnumber d
Return
number: \[ c + (d - c) \cdot \sqrt{\frac{x - a}{b - a}} \]
Error
if \(a > b\), or \(c > d\), or \(x\) not in range \([a,b]\).
See
QuadraticScaling
PowerScaling

PowerScaling(number x, number n, number a, number b, number c, number d)

Power scaling of \(x\) from range \([a,b]\) to \(x^n\) in \([c,d]\).

Flexible control of the non-linearity. QuadraticScaling use \(x^2\), here we add \(n\) argument:

  • if \(n > 1\), low values are compressed, high values are expanded,
  • if \(0 < n < 1\) low values are expanded, high values are compressed,
  • if \(n = 1\) the scaling is linear.

ParameterTypeDefaultDescription
xnumber x
nnumber Power, positive number
anumber a
bnumber b
cnumber c
dnumber d
Return
number: \[ c + (d - c) \cdot \left(\frac{x - a}{b - a}\right)^n \]
Error
if \(n \leq 0\), or \(a > b\), or \(c > d\), or \(x\) not in range \([a,b]\).

Issue