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

Classes

ClassSummary
INIRough INI configuration file reader and writer.
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.
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
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.
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.
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?
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.
tableFileReadLines(string path, int stringEncoding, int crlf, boolean errorIfNotFound)
Syntaxic sugar to read all lines of a file, and return a table of them.
 FileWriteLines(string path, table lines, function formatFunc, int stringEncoding, int crlf)
Syntaxic sugar to writes a table of strings as lines in a file.
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.
tableGetFilesInFolder(string folder, string mask, boolean recursive, boolean fullPath)
BrowseFolder(...) needs a callback function, and has a bug: here is a fixed and simplified version.
stringGetGlobalSetting(string settingName)
Reads a line from global settings file, when MyrScript has no built-in function to get the value of a global setting.
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
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?
 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.
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)
Menu to pick multiple value in a list of items as checkboxes.
 MenuSingleChoice(string title, Lexicon lexicon, datas)
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.
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().
 SMAlert(string msg)
Add accessibility to built-in Alert() function.
intSMApplyToAllSelectedSymbols(Score score, function processFunc)
Apply a function to all selected symbols, individually selected or continous selection.
intSMApplyToAllSymbols(Score score, Staff staff, int firstBar, int lastBar, function processFunc)
Apply a function to all symbols in the score, or staff, or in a rang eof bars.
booleanSMConfirmation(string msg)
Add accessibility to built-in Confirmation() function.
 SMMessage(string msg)
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)
Say the text if text to speech is enable for visually impaired people (screen reader).
stringScriptReadVersion(string file)
Read the version of a script.
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.
booleanSortTargets(Score score)
Sort the targets (rehearsal marks) by bar number.
 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.
 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.
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.
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.
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.
 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

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.

ParameterTypeDefaultDescription
expr  expr
Return
boolean: true if expr is true, false otherwise.

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

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.

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") --> ">"

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)

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.

ParameterTypeDefaultDescription
scoreScore score
processFuncfunction Function with a singl Symbol argument, and returns true if symbol has been processed.
Return
int: Number of processed symbols
Error
if score is not a Score or processFunc is not a function.
See
SMApplyToAllSymbols

SMApplyToAllSymbols(Score score, Staff staff, int firstBar, int lastBar, function processFunc)

Apply a function to all symbols in the score, or staff, or in a rang eof bars.

ParameterTypeDefaultDescription
scoreScore score
staffStaffnilnil menas all staves.
firstBarint1First bar to start applying the function.
lastBarintscore.NumberOfBarsLast bar to stop applying the function.
processFuncfunction Function with a singl Symbol argument, and returns true if symbol has been processed.
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

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.

  • 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)

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
Return
string: Found value, or nil if not found.

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

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)
  )

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

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.

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

ScreenReader(string text)

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

ParameterTypeDefaultDescription
textstring text

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)

Add accessibility to built-in Message() function.

ParameterTypeDefaultDescription
msgstring msg

MenuSingleChoice(string title, Lexicon lexicon, datas)

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
Return
choosen value (or caption), or nil if user canceled the choice.
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
 else -- no selection, user canceled the choice
 end

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

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.
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

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.

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

GetFilesInFolder(string folder, string mask, boolean recursive, boolean fullPath)

BrowseFolder(...) needs a callback function, and has a bug: here is a fixed and simplified version.

ParameterTypeDefaultDescription
folderstring Folder name
maskstring"*.*"Mask to search file, e.g. "*.myr", "a*.*"
recursivebooleanfalsetrue to browse sub-folders
fullPathbooleanfalsetrue returns the full path, false returns only file names
Return
table: File names: array of string, in alphabetic order

FileReadLines(string path, int stringEncoding, int crlf, boolean errorIfNotFound)

Syntaxic sugar to read all lines of a file, and return a table of them.

Note:

  • encoding is supposed to be UTF-8 BOM and lines terminated by Macintosh CR.
  • Convenient for small files when full content have to been read and stored.

ParameterTypeDefaultDescription
pathstring The full path of the file to read.
stringEncodingintUTF8_STR_ENCODINGString encoding constant from MSDefine, e.g. UNKNOWN_STR_ENCODING
crlfintMAC_CRCarriage return constant from MSDefine, MAC_CR, LINUX_CR, WIN_CR, UNKNOWN_CR
errorIfNotFoundboolean (defaut=true) Throw error if file is not found, else return an empty table.
Return
table: Table of string, one item per line
Errors
if argument is not a string
if file can't be read
See
FileWriteLines
Example


 local lines = FileReadLines("/path/to/myConfigFile.txt")
 print(lines[1]) -- first line of the config file

FileWriteLines(string path, table lines, function formatFunc, int stringEncoding, int crlf)

Syntaxic sugar to writes a table of strings as lines in a file.

Collection and Map are also handled, and an optional formating function can transform lines before writing. Notes:

  • The file is overwritten,
  • Encoding is UTF-8 BOM and lines are terminated by Macintosh CR.

ParameterTypeDefaultDescription
pathstring The full path of the file to write
linestable The lines to write, can be a table, a Collection or a Map
formatFuncfunctionnilFormatting function that receive two arguments and must return a string that will be written into the file. Arguments are:
  • if simple table: int table index and the value,
  • if Collection: a int counter and a Collection item,
  • if Map, key and value (an entry of the Map).
If formatFunc is nil then table and Collection prints their values, Map prints key and values separated by a space char.
stringEncodingintUTF8_STR_ENCODINGString encoding constant from MSDefine, e.g. HTML_STR_ENCODING
crlfintMAC_CRCarriage return constant from MSDefine, MAC_CR, LINUX_CR, WIN_CR, UNKNOWN_CR
Errors
if arguments have bad type.
if file can't be written.
See
FileReadLines
Examples


 local lines = FileReadLines("/path/to/myConfigFile.txt")
 lines[1] = "0" -- change a value in the config file
 FileWriteLines("/path/to/myConfigFile.txt", lines)


 local map = Map:new("number", "string", SORT_ASCENDING)
 map:put(1, "one"); map:put(2, "two"); map:put(3, "three")
  FileWriteLines("/path/to/file/count.txt", map,
   function(key,value) return tostring(key).."="..strupper(value); end)
 )
 -- outputs 3 lines 1=ONE, 2=TWO and 3=THREE

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.

ScriptReadVersion(string file)

Read the version of a script.

Look for the --VERSION: x.y in first 30 lines of source code.

ParameterTypeDefaultDescription
filestring Script file name (or full path)
Return
string: A version in the x.y.z or yyyyMMdd form (as source code), or nil if file doesn't exist or version not found.

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.

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

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
Example


 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}

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
Example


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

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)

Issue