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:
- SMFiles
- SMJavaCollections
- SMLexicon
- SMLogger
- SMStrings
- SMTheory
- Sylvain Machefert
Class
| Class | Summary |
|---|---|
| Stopwatch | Stopwatch (French: chronomètre) to measure elapsed time. |
Sections
| Section | Summary |
|---|---|
| Accessibility | Accessibility functions, mostly audio messages. |
| Assertions | Assertion functions, that extend Lua assert(...) standard function. |
| Bars | Bars utility functions. |
| Batch | Batch processing. |
| BooleanAlgebra | Boolean algebra functions. |
| Chords | Chord class and other chords utility functions, like extracting chords from the chord line of a staff. |
| Clefs | Clefs utility functions. |
| Colors | Color utility functions. |
| Curves | Parameter curves utility functions. |
| Debug | Debugg and log functions. |
| DevTools | Some dev tools for script authors |
| Diagrams | Chord diagrams utility functions |
| Drums | Drums grids, play and other utility function. |
| Durations | Clock and durations utility functions
|
| Dynamics | Dynamics utility functions |
| FXProcessors | FXProcessor handling utility functions. |
| Files | Files utility functions |
| Fonts | Font utility functions. |
| FreeObjects | FreeObject utility functions. |
| Graphics | Utility functions for images, drawing on Graph |
| Inputs | Input functions, to ask user to enter number, select in a list of choices, two values as XY coordinates. |
| Instruments | Harmony's Instruments utility functions |
| Internet | Internet functions. |
| Intervals | Interval constants |
| KeySignatures | KeySignature utility functions. |
| MIDI | MIDI utility functions. |
| Numbers | numbers utility functions. |
| Ornaments | Ornaments utility functions |
| Pictures | Staff picture utility functions |
| Play | Play utility functions: play the score, play a sound... |
| Preferences | Preferences functions: workaround for bogus or missing function that read global preferences. |
| Reflection | MyrScript reflection Reflective programming or reflection is the ability of a script to examine, introspect, |
| Rules | Rules utility functions |
| Scores | Score utility functions |
| StaffTexts | StaffText utility functions |
| Staves | Staff utility functions |
| StavesGroups | StavesGroup utility functions |
| StorageAreas | StorageArea utility function |
| Strings | strings utility functions |
| Symbols | Symbols (notes, rests...) utility functions |
| Syntax | Extend Lua language: assertions, logging, switch/case, bit operations... |
| Tables | tables utility functions. |
| Targets | Target utility functions. |
| Tempo | Tempo utility functions |
| Unicode | Unicode representation of some musical symbols, and Unicode string functions. |
| Views | View utility functions |
Summary
| Constant | Type | Summary |
|---|---|---|
| BAR_STATE_AFTER_PRINT_REGION | int | Bar state visibility: not visible, after last printed bar |
| BAR_STATE_BEFORE_PRINT_REGION | int | Bar state visibility: not visible, before first printed bar |
| BAR_STATE_MULTI_FIRST | int | Bar visibility state: visible, first bar of a multi-rest or multi-repeat. |
| BAR_STATE_MULTI_LAST | int | Bar visibility state: not visible, last bar of a multi-rest or multi-repeat. |
| BAR_STATE_MULTI_MIDDLE | int | Bar visibility state: not visible, inside (but not last bar of) a multi-rest or multi-repeat. |
| BAR_STATE_UNDEFINED | int | Bar visibility state: undefined: should not happen. |
| BAR_STATE_VISIBLE | int | Bar visibility state: normal, visible. |
| Return type | Function and summary |
|---|---|
| boolean | AND(boolean ...) AND function in boolean algebra, that accepts undefined number of arguments. |
| AddImagesDirectory(string path) Add a directory where script can search for pictures. | |
| int | AdjustStavesGroupSymbolPosition(Score score, table groups) Experimental: Adjust horizontal and vertical staves group symbole (braces and brackets). |
| ArrayClear(table t) Optimization of clearing a table. | |
| boolean | ArrayContains(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. | |
| int | BatchExecute(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. | |
| int | BinNot(int a, int bits) NOT bitwise operation MyrScript comes with BinAnd(...), BinOr(...), BinXor(...), BinShl(...), BinShr(...) but not the NOT bitwise operation. |
| string, string, int | ChooseColor(string object, table suggestedColors, selected) Ask the user to choose one color in a menu. |
| string, int, int, string | ChooseFont(string object, table suggestedFonts, selected) Ask the user to choose one font in a menu. |
| int | ChooseNoteHeadShape(int defaultValue) Open a dialog to choose a note head shape. |
| table | ChooseStaves(Score score, boolean multiple, boolean visibleOnly, function filterFunc, function selectFunc, int minNbOfChoice, int maxNbOfChoice) Ask the user to choose one or multiple staves. |
| table | ChooseStavesGroups(Score score, boolean multiple, boolean visibleOnly, function filterFunc, function selectFunc) Ask the user to choose one or multiple staves groups. |
| Target | ChooseTarget(Score score, string prompt, int selectedBar, string selectedName) Select a Target (rehearsal mark) in the Score. |
| int | ChooseView(Score score, boolean index, int (default=current) Ask the user to choose one view, or a value for ViewIndex. |
| string | CompareMyrScriptVersion(string version) Is MyrScript =, < or > version x.y.z? |
| int | CompareSymbolsByPitch(Symbol a, Symbol b) Compare two Symbols by pitch, then displayed height. |
| table, int, int, int | CompareTables(table lines1, table lines2) Compare two tables, returns a diff-like format. |
| string | CompareVersions(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. | |
| int | CopyFreeObjects(Score src, Score dest) Copy free objects from one Score to another. |
| int, int | CopyOrnaments(Symbol from, Symbol to) Copy all ornaments from a Symbol to another one. |
| int | DeleteAllFreeObjects(Score score) Delete all free objects from a score, without confirmation. |
| int | DeleteAllTargets(Score score, boolean preserveScore) Delete all targets (rehearsal marks) from a score. |
| int | DeleteDisabledCurves(Staff staff) Remove the parameter curves that have been disabled. |
| int | DeleteEmptyCurves(Staff staff) Remove the empty parameter curves when they have no values. |
| int | DeleteHiddenFreeObjects(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. | |
| int | DeleteUselessClefs(Staff staff) Delete useless clef change that are visible clefs with no changes. |
| Deserialize(string str) Deserialize a string into object. | |
| int | DontSplitTwoAndFourRepeats(Score score, int firstBar, int lastBar) In current view, avoid split (end of line) in the middle of %2 and %4 bar-repeats. |
| boolean | DynamicIsOttava(Dynamic dynamic) Is dynamic an ottava (8va, 8vb, 15va or 15vb)? |
| boolean | DynamicIsPedal(Dynamic dynamic) Is dynamic an pedal (Ped. |
| boolean | DynamicIsTempo(Dynamic dynamic) Is dynamic a Tempo? |
| boolean | DynamicIsVelocity(Dynamic dynamic) Is dynamic a velocity (power) change? |
| table | ElementsToTable(...) Transforme a list (multiple returned values from a function call) to a table. |
| boolean | EnsureObjectInStaffArea(Score score, Staff staff, obj) Ensure an object is in the Staff area, move it vertically if needed. |
| string, int, int, string | EnterFont(string font, face, number size, string color) Ask the user to choose font, face, size and color using the built-in EditTextStyle() dialog. |
| number | EnterNumber(string text, number defaultValue, number minValue, number maxValue) Ask the user to enter a number. |
| number, number | 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. |
| string, string | FontFaceNumberToString(int face) Convert a font face (sum of FACE_* constants from MSDefine) to strings. |
| int | FontFaceStringToNumber(string str) Convert a font face as string like "BI" into sum of FACE_* constants from MSDefine. |
| table | GetBarVisibilityState(Score score, int firstBar, int lastBar) Get the visibility state of all bars between firstBar and lastBar. |
| table | GetChordsFromStaff(Score score, Staff staff, boolean held) Get the chords of a Staff from the chord line and return detailed informations. |
| Collection | GetDynamicsThatApplyToStaff(Score score, Staff staff) Get all Dynamic that apply to the specified Staff. |
| GetGlobalSetting(string settingName, boolean multiple) Reads a line from global settings file, when MyrScript has no built-in function to get the value of a global setting. | |
| KeySignature | GetKeySignatureAtBar(Staff staff, int barN, boolean visibleOnly) Get the key signature at requested bar of requested staff. |
| table, int | GetMergedStaves(Staff staff) Get all staves merged with staff, included. |
| table, int | GetOverlappingSymbols(Symbol sym) Get all symbols (notes and rests) from merged staves, which begin time is before sym end time, and end time is after sym begin time. |
| string, int, int, string | GetPreferredFont(string object) Get preferred font from Global settings > Fonts |
| table | GetStavesGroups(Score score, Staff staff) Get all StavesGroups of the score or containing staff if this argument is provided. |
| table | GetStavesInGroup(StavesGroup sg) Return an array of staves in StavesGroup sg |
| table, int | GetSymbolsInChord(Symbol sym) Return all symbols in chord with sym (included), in its staff and merged ones. |
| number, int, Dynamic | GetTempoAtTime(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. | |
| boolean | IN(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. | |
| boolean | InstrumentIsUsed(Score score, Instrument instr, boolean excludeMutedStaves) Is instr Instrument used in score ? |
| boolean | IsLuaClass(string className) Is className the name of a class? |
| boolean | IsPowerOfTwo(number n) Is n a number power of 2? |
| boolean | IsScreenReaderActive() Is there a screen reader, a voice that assist visually impaired user? |
| boolean | IsThemeSoundsActive() Are interface sounds active in scripts using SMDialog and SMMenu? |
| JumpAndSelectBar(Score score, int barN, Staff staffBegin, Staff stafEnd) Jump to the requested bar number and select it, all staves or the requested staff if not nil. | |
| number | LinearScaling(number x, number a, number b, number c, number d) Linear scaling (or linear transformation) of \(x\) from range \([a,b]\) to \([c,d]\). |
| int | LoadScoreAppearance(Score score, string setName) Load score appearance settings from a file saved by SaveScoreAppearance(...). |
| table | MenuMultipleChoice(string title, Lexicon lexicon, datas, int minNbOfChoice, int maxNbOfChoice, string header) Menu to pick multiple value in a list of items as checkboxes. |
| MenuSingleChoice(string title, Lexicon lexicon, datas, string header, boolean hideRadios) Menu to pick one value in a list of items as radio buttons. | |
| table | 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. |
| MidiSendCC(int interface, int channel, int controller, int value) Send a control change (CC) message to a MIDI device. | |
| MuteScreenReader(int delay) Temporarily mute the Screen Reader for a short delay. | |
| boolean | 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. |
| boolean | NIL(...) Return true if all arguments are nil |
| boolean | NOR(boolean ...) NOR (NOT OR) function in boolean algebra, that accepts undefined number of arguments and returns true if all arguments are not true. |
| boolean | NOT(boolean b) NOT function in boolean algebra. |
| boolean | NOT_NIL(...) Return true if all arguments are not nil |
| number | NumberOfDecimals(number n) Get the number of decimals of a number |
| boolean | OR(boolean ...) OR function in boolean algebra, that accepts undefined number of arguments. |
| PlayFromBar(Score score, int barNumber, boolean showKaraoke, boolean scrollMusic, boolean followMusic, int metronomeBars) Start playing music from specified bar. | |
| PlayNote(Symbol symbol) Plays a note, shortcut and fix for Staff.PlayNotes(). | |
| PlayThemeSound(string soundName, boolean wait) Play a "theme" sound, if set to active. | |
| number | PowerScaling(number x, number n, number a, number b, number c, number d) Power scaling of \(x\) from range \([a,b]\) to \(x^n\) in \([c,d]\). |
| number | QuadraticScaling(number x, number a, number b, number c, number d) Quadratic scaling of \(x\) from range \([a,b]\) to \([c,d]\). |
| RecentScriptsAdd(string path, string name) In debug mode, add current script to the "Recent scripts" list. | |
| SMAlert(string msg) Add accessibility to built-in Alert() function. | |
| int | SMApplyToAllSelectedSymbols(Score score, function processFunc, boolean excludeSpecials) Apply a function to all selected symbols, individually selected or continous selection. |
| int | SMApplyToAllSymbols(Score score, staves, int firstBar, int lastBar, function processFunc, boolean excludeSpecials) Apply a function to all symbols in the score, or staff, or in a range of bars. |
| boolean | SMConfirmation(string msg) Add accessibility to built-in Confirmation() function. |
| string | SMEnterString(string text, string defaultValue) Call to EnterString with accessibility and assertions checks |
| Symbol | SMFirstSelectedSymbol(Score score, Staff staff, boolean ignoreGhostRest) Returns the first selected symbol (range or individual selection) of the staff or the whole score. |
| Symbol | SMLastSelectedSymbol(Score score, Staff staff, boolean ignoreGhostRest) Returns the last selected symbol (range or individual selection) of the staff or the whole score. |
| SMMessage(string msg, boolean skipVisual) Add accessibility to built-in Message() function. | |
| string, int | SMPitchToString(int pitch, int preferredAccidental, int compatible, string preferredNote) Extension and bugfix for builtin PitchToString function. |
| int, int | SMStringToPitch(string name) Extension and bugfix for builtin StringToPitch function. |
| SaveScoreAppearance(Score score, string setName, boolean full) Save score appearance settings in a file. | |
| ScreenReader(string text, boolean wait) Say the text if text to speech is enable for visually impaired people (screen reader). | |
| Symbol, Staff | SearchNextSymbol(Score score, staves, from, function matcher) Search next symbol with custom matcher function, in whole score or a list of staves, at a time position or after a symbol. |
| Symbol, Staff | SearchPreviousSymbol(Score score, staves, from, function matcher) Search previous symbol with custom matcher function, in whole score or a list of staves, at a time position or before a symbol. |
| string | Serialize(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. | |
| boolean | SetSlurDirection(Symbol note, boolean isUp) Set slur direction up or down. |
| int | ShowHiddenClefs(Staff staff) Show hidden clefs where needed. |
| boolean | SortTargets(Score score) Sort the targets (rehearsal marks) by bar number. |
| number | SquareRootScaling(number x, number a, number b, number c, number d) Square root scaling of \(x\) from range \([a,b]\) to \([c,d]\). |
| StaffSetAmbitus(Score score, Staff staff, boolean state) Set the ambitus enabled or disabled for staff, and also at score's level else ambitus won't display. | |
| string | StavesGroupName(StavesGroup sg) Return the name (title) of sg or build a name from its first and last grouped staves. |
| int | StorageAreaClear(StorageArea storage, string tag4) Remove all items from the StorageArea storage for tag tag4. |
| int, int, boolean, boolean, string | SymbolGetAccidental(Symbol sym) Return accidental data for a Symbol, handles microtonals. |
| boolean | SymbolIsDotted(Symbol sym) Tell if the Symbol is displayed with dot(s). |
| boolean | SymbolIsMicrotonalAccidental(Symbol sym) Is the note played with a microtonal accidental? |
| boolean | SymbolIsTieVisible(Symbol note) Is the note tied? |
| boolean | SymbolSetAccidentalVisibility(Symbol sym, boolean visible) Change the accidental visibility of a Symbol. |
| boolean | SymbolsAreContiguous(Symbol a, Symbol b) Tell if two Symbols are contiguous. |
| boolean | SymbolsCanBeTied(Symbol ...) Symbols can be tied if they are all contiguous and have same played and displayed pitch. |
| TableToElements(table t) Bugfix version of MSLibrary's PushAllTableElts(t), return all elements of a table as multiple return values. | |
| TargetHideBarNumbers(Score score) Hide bar numbers at bar that display a rehearsal mark, for all views. | |
| TargetSplitMultiRests(Score score) Split multi-rests at all visible rehearsal marks, for all views. | |
| int | TargetVisibility(Score score, Target target, boolean visible) Turn one or all targets visible or hidden. |
| UnMuteScreenReader() After MuteScreenReader(...) and the massive actions that would have produced unaudible audio messages, unmute the Screen Reader. | |
| boolean | XOR(boolean a, boolean b) XOR function in boolean algebra. |
| boolean | assertBoolean(b, string errorMessage, boolean visual) Assert b is a boolean ( true or false, not nil), else throw errorMessage. |
| boolean | assertDialog(dialog, string errorMessage, boolean visual) Assert dialog is a Dialog, else throw errorMessage. |
| boolean | assertEquals(expr, expected, string Text, boolean visual) Assertion an expression or function call equals an expected result. |
| boolean | assertEqualsIgnoreCase(expr, expected, string Text, boolean visual) Assertion an expression or function call equals an expected result; if both are string, the cases are ignored. |
| boolean | assertExpression(expr, string errorMessage, boolean visual) Assert an expression result is true. |
| boolean | assertFalse(b, string errorMessage, boolean visual) Assert b is false, else throw errorMessage. |
| boolean | assertFunction(f, string errorMessage, boolean visual) Assert f is a function, else throw errorMessage. |
| boolean | assertInArray(value, table t, string text, boolean visual) Assert a value is found in a table. |
| boolean | assertNegativeNumber(n, string errorMessage, boolean visual) Assert n is a negative number, else throw errorMessage. |
| boolean | assertNil(n, string errorMessage, boolean visual) Assert n is nil, else throw errorMessage. |
| boolean | assertNotEmptyString(s, string errorMessage, boolean visual) Assert s is a not-nil and not empty string, else throw errorMessage. |
| boolean | assertNotNil(n, string errorMessage, boolean visual) Assert n is not nil, else throw errorMessage. |
| boolean | assertNotZero(n, string errorMessage, boolean visual) Assert n is a number but not 0, else throw errorMessage. |
| boolean | assertNumber(n, string errorMessage, boolean visual) Assert n is a not-nil number, else throw errorMessage. |
| boolean | assertPositiveNumber(n, string errorMessage, boolean visual) Assert n is a positive number, else throw errorMessage. |
| boolean | assertScore(s, string errorMessage, boolean visual) Assert s is a Score, else throw errorMessage. |
| boolean | assertString(s, string errorMessage, boolean visual) Assert s is a not-nil string (possibly empty), else throw errorMessage. |
| boolean | assertTable(t, string errorMessage, boolean visual) Assert t is a table, else throw errorMessage. |
| boolean | assertTrue(b, string errorMessage, boolean visual) Assert b is true, else throw errorMessage. |
| boolean | assertType(t, string expectedType, string errorMessage, boolean visual) Assert type(t) is a expectedType, else throw errorMessage. |
| int | bin2int(string s, boolean signed) Converts binary number (string containing only "0" and "1") to number. |
| boolean | bool(expr) Converts expr to a boolean. |
| number | bound(number n, number mini, number maxi) Ensure number n is within bounds [mini:maxi]. |
| table | case(string _type, _params, function _func, boolean _break) Create a case for switch() function. |
| number | cm_to_dpi72(number n) Convert a centimeter value into 72 DPI pixels. |
| table | default(function _func) Create a default case for switch() function. |
| number | dpi72_to_cm(number n) Convert a 72 DPI pixel value into centimeters. |
| number | duration_256th_of_quarter_to_ms(int nbOf256th, number tempo) Convert 256ths of quarter to milliseconds, according to tempo. |
| int | 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. |
| int | duration_ms_to_256th_of_quarter(number milliseconds, int noteDuration, number tempo) Convert at duration in milliseconds to 256th of quarter, according to tempo |
| int | duration_ms_to_note(number milliseconds, number tempo) Convert a duration in milliseconds to a note duration according to tempo. |
| int | 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. |
| number | duration_note_to_ms(int noteDuration, number tempo) Convert a note duration to milliseconds, according to tempo. |
| int | 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. |
| number | duration_percent_of_note_to_ms(int percent, int noteDuration, number tempo) Convert a percentage of note duration to milliseconds, according to tempo. |
| number | flag_clear(number set, number flag) Clear a bit to 0, the bit can be seen as a flag. |
| number | flag_set(number set, number flag) Set a bit to 1, the bit can be seen as a flag. |
| boolean | flag_test(number set, number flag) Test if a bit is set, the bit can be seen as a flag. |
| string | gettagname(obj) Return, if known, the tag name of an object. |
| int | hex2int(string s, boolean signed) Converts hexadecimal number (string containing 0-9a-fA-f) to number. |
| boolean | isTable(obj) Returns true if obj is a table or a MyrScript object represented as a table such as Score or Target. |
| longest_common_subsequence(a, b) Longest Common Subsequence (LCS) algorithm, basis for data comparison. | |
| number | round(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. | |
| table | table_unique(table tab) Remove duplicates from a table |
| tdebug(...) Return the structure of a table, Collection or Map for debugging to the console. | |
| throw(string exception, boolean visual, function catch) Log (console and/or file) and stop the script with error(). | |
| string | tobin(int n, int size, string separator) Converts a number to a binary string (containing only 0 and 1) |
| 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 |
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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| file | string | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| exception | string | Error message | |
| visual | boolean | false | Visual alert. If true, does not stop the script with a console error. Your script must handle this to stop gracefully. |
| catch | function | nil | If 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | n | ||
| errorMessage | string | Message to throw: by convention, the function where it happen, and the argument's or variable's name.": expected number, got ..." will be concatenated. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | n | ||
| errorMessage | string | 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. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | n | ||
| errorMessage | string | 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. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | n | ||
| errorMessage | string | 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. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| s | s | ||
| errorMessage | string | Message to throw: by convention, the function where it happen, and the argument's or variable's name.": expected string, got ..." will be concatenated. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| s | s | ||
| errorMessage | string | 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. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| b | b | ||
| errorMessage | string | Message to throw: by convention, the function where it happen, and the argument's or variable's name.": expected boolean, got ..." will be concatenated. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| b | b | ||
| errorMessage | string | Message to throw: by convention, the function where it happen, and the argument's or variable's name.": expected true, got ..." will be concatenated. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| b | b | ||
| errorMessage | string | Message to throw: by convention, the function where it happen, and the argument's or variable's name.": expected false, got ..." will be concatenated. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| t | t | ||
| errorMessage | string | Message to throw: by convention, the function where it happen, and the argument's or variable's name.": expected table, got ..." will be concatenated. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| f | f | ||
| errorMessage | string | Message to throw: by convention, the function where it happen, and the argument's or variable's name.": expected function, got ..." will be concatenated. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | n | ||
| errorMessage | string | Message to throw: by convention, the function where it happen, and the argument's or variable's name.": expected nil, got ..." will be concatenated. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | n | ||
| errorMessage | string | 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. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| expr | Result of an expression, e.g. x < y | ||
| errorMessage | string | Nothing is concatenated, the message must be full and self-explainatory. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| expr | Result of an expression | ||
| expected | Expected result | ||
| Text | string | to print on console and throw if expr ~= expected | |
| visual | boolean | false | Visual 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:
trueif assertion is correct,nil(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - Error
- If expr ~= expected
assertEqualsIgnoreCase(expr, expected, string Text, boolean visual)
Assertion an expression or function call equals an expected result; if both are string, the cases are ignored.
This is useful for unit tests.
| Parameter | Type | Default | Description |
|---|---|---|---|
| expr | Result of an expression | ||
| expected | Expected result | ||
| Text | string | to print on console and throw if expr ~= expected | |
| visual | boolean | false | Visual 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:
trueif assertion is correct,nil(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - Error
- If
<strlower(expr) ~= strlower(expected)
assertInArray(value, table t, string text, boolean visual)
Assert a value is found in a table.
| Parameter | Type | Default | Description |
|---|---|---|---|
| value | number or string. nil always fails the assertion. | ||
| t | table | List of values in which value is searched for. | |
| text | string | Text to print on console and throw if expr ~= expected | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| dialog | dialog | ||
| errorMessage | string | Message to throw: by convention, the function where it happen, and the argument's or variable's name.": expected Dialog, got ..." will be concatenated. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| s | s | ||
| errorMessage | string | Message to throw: by convention, the function where it happen, and the argument's or variable's name.": expected Score, got ..." will be concatenated. | |
| visual | boolean | false | Visual 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:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| t | t | ||
| expectedType | string | expectedType | |
| errorMessage | string | Message to throw: by convention, the function where it happen, and the argument's or variable's name.": expected 'expectedType', got ..." will be concatenated. | |
| visual | boolean | false | Visual 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:
trueif assertion is correct,nil(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - See
- assertDialog
- assertFunction
- assertNumber
- assertScore
- assertString
- assertTable
- Example
assertType(s, "Staff", "MyFunction, argument #1") --> if s is not a Staff, this print --> ERROR MyFunction, argument #1, expected Staff, got ...
bool(expr)
Converts expr to a boolean.
expr can be a number, an expression or a string. This a convenient way to ensure that the result of an expression is never nil where it may cause troubles or unknown behaviour: myDialogItem.IsVisible = bool(a_long_expression) is a syntaxic sugar for myDialogItem.IsVisible = (a_long_expression) or false
| Parameter | Type | Default | Description |
|---|---|---|---|
| expr | expression, number, string... |
- Return
- boolean:
trueifexpr == true or expr == "1",falseotherwise. - Example
print(bool(nil)) --> 0 print(bool(3)) --> 0 print(bool("hello")) --> 0 print(bool(1 == 3)) --> 0 print(bool(3 < 7)) --> 1 print(bool("1")) --> 1
NOT(boolean b)
NOT function in boolean algebra.
Lua not x means "not nil", so not true is always true. NOT(true) returns nil (for false) so it can be used safely in if..then statements. If you want to obtain a real false, use the bool() function: a = bool(NOT(<expression>))
| Parameter | Type | Default | Description |
|---|---|---|---|
| b | boolean | b |
- Return
- boolean:
trueifb==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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| ... | boolean | Undefined number of arguments. |
- Return
- boolean:
trueif all arguments aretruenil(for false) if at least one argument is nottrue.
- 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
| Parameter | Type | Default | Description |
|---|---|---|---|
| ... | boolean | Undefined number of arguments. |
- Return
- boolean:
trueif at least one argument istruenil(for false) if no argument istrue.
- 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| ... | boolean | Undefined number of arguments. |
- Return
- boolean:
trueif at least one argument is nottrue,nil(for false) if all arguments aretrue.
- 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| ... | boolean | Undefined number of arguments. |
- Return
- boolean:
trueif all arguments are nottrue,nil(for false) if at least one argument istrue.
- Error
- if less than two arguments
XOR(boolean a, boolean b)
XOR function in boolean algebra.
| Parameter | Type | Default | Description |
|---|---|---|---|
| a | boolean | a | |
| b | boolean | b |
- Return
- boolean:
trueif only one of a and b istrue,nil(for false) if a and b have same boolean value.
NIL(...)
Return true if all arguments are nil
| Parameter | Type | Default | Description |
|---|---|---|---|
| ... | ... |
- Return
- boolean:
trueif all arguments arenil,nil(for false) if at least one argument is notnil.
NOT_NIL(...)
Return true if all arguments are not nil
| Parameter | Type | Default | Description |
|---|---|---|---|
| ... | ... |
- Return
- boolean:
trueif all arguments are notnil,nil(for false) if at least one argument isnil.
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).
| Parameter | Type | Default | Description |
|---|---|---|---|
| expr | boolean | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| 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:
trueif the list contains term,nil(for false) if the list doesn't contains term - See
- ArrayContains
CompareVersions(string a, string b)
Compare two version numbers in x.y.z string format.
| Parameter | Type | Default | Description |
|---|---|---|---|
| a | string | a | |
| b | string | b |
- Return
- string:
"<", ">"or"="if a is lower, greater or equal to b. - Example
CompareVersions("9.9.7", "9.9.6") --> ">"
CompareMyrScriptVersion(string version)
Is MyrScript =, < or > version x.y.z?
As Application.MyrScriptVersion is a string, comparison may fail in the future, "10.1.1" is greater than "9.9.9" but string comparison will stay it's lower (because "1" < "9").
| Parameter | Type | Default | Description |
|---|---|---|---|
| version | string | Version to compare, in x.y.z form (e.g.: "1.6.9") |
- Return
- string:
"<", ">"or"="ifApplication.MyrScriptVersionis lower, greater or equal to version.
PlayFromBar(Score score, int barNumber, boolean showKaraoke, boolean scrollMusic, boolean followMusic, int metronomeBars)
Start playing music from specified bar.
Target.PlayMusic() is bogus; here is a work-around.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | The score to play | |
| barNumber | int | The bar to start from, could be Target.Bar | |
| showKaraoke | boolean | user prefs | Display karaoke if score has lyrics? |
| scrollMusic | boolean | user prefs | Scrolls the score while playing? |
| followMusic | boolean | user prefs | Open follow tune dialog? |
| metronomeBars | int | user prefs | Number 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| preserveScore | boolean | false | Preserve 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| t | table | The table to clear. |
ArrayContains(table tab, term)
Does tab contains term?
| Parameter | Type | Default | Description |
|---|---|---|---|
| tab | table | A table of numbers or strings | |
| term | A number or a string to find in tab |
- Return
- boolean:
true, ornil(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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| obj | A Lua object |
- Return
- string: The tag name,
nilif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| className | string | className |
- Return
- boolean:
trueif it's a class,nilfor 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| ... | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| term | string or number, that can be compared | ||
| cases | table | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| _type | string | Accepted values are:
| |
| _params | A number, a string, or a table:
| ||
| _func | function | _func | |
| _break | boolean | true | true to stop after this case, false to continue and execute function of next case(s) until a case breaks. |
default(function _func)
Create a default case for switch() function.
| Parameter | Type | Default | Description |
|---|---|---|---|
| _func | function | that will receive the tested term as parameter |
CopyFXProcessor(FXProcessor source, FXProcessor dest)
Copy all parameters from a FXProcessor to another one.
| Parameter | Type | Default | Description |
|---|---|---|---|
| source | FXProcessor | The FXProcessor to copy | |
| dest | FXProcessor | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| instr | Instrument | The instrument | |
| fxproc | FXProcessor | The FXProcessor which properties will be copied in the instrument's FX Processor |
SMApplyToAllSelectedSymbols(Score score, function processFunc, boolean excludeSpecials)
Apply a function to all selected symbols, individually selected or continous selection.
MSLibrary's ApplyToAllSelectedSymbols(...) function doesn't handle individually selected symbols, and browse from last to first, which is safe for symbol deletion. This customized browse selected notes on all staves from first to last, not convenient for deletion. It can skips ghost rests and special symbols, handles individual and continuous (range) selection.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| processFunc | function | Function with two Symbol and Staff arguments, which returns true (= 1) if symbol has been processed, -1 to stop the process. Other returned values are ignored, process continue to next symbol. | |
| excludeSpecials | boolean | false | Exclude ghost rest, mesure repeat (%, %2, %4), and unison in divisi (//)? |
- Return
- int: Number of processed symbols
- Error
- if score is not a Score or processFunc is not a function.
- See
- SMApplyToAllSymbols
SMApplyToAllSymbols(Score score, staves, int firstBar, int lastBar, function processFunc, boolean excludeSpecials)
Apply a function to all symbols in the score, or staff, or in a range of bars.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| staves | nil | ||
| firstBar | int | 1 | First bar to start applying the function. |
| lastBar | int | score.NumberOfBars | Last bar to stop applying the function. |
| processFunc | function | Function with two Symbol and Staff arguments, which returns true (= 1) if symbol has been processed, -1 to stop the process. Other returned values are ignored, process continue to next symbol. | |
| excludeSpecials | boolean | false | Exclude ghost rests, bar repeats (%, %2, %4) and unison in divisi (//)? |
- Return
- int: Number of processed symbols
- Error
- if arguments have wrong types.
- See
- SMApplyToAllSelectedSymbols
PlayNote(Symbol symbol)
Plays a note, shortcut and fix for Staff.PlayNotes().
Play only one note (the symbol parameter), in its context (tempo at its Time position), duration, velocity and pitch. Fix the no-sound bug when pitch==0 on grid drum staves.
| Parameter | Type | Default | Description |
|---|---|---|---|
| symbol | Symbol | (note) to play |
SetDrumGridsDivision(Score score, int numberOfDivisions)
Set the Staff.DefaultDrumDivision to all drum grid-staves.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| numberOfDivisions | int | Number of division per beat |
- Error
- if score is nil or numberOfDivisions < 1
round(number num, int numberOfDecimals)
Round a number.
| Parameter | Type | Default | Description |
|---|---|---|---|
| num | number | Number to round() | |
| numberOfDecimals | int | 0 | Number 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
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | number | 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)
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | number | n | |
| mini | number | Minimal value | |
| maxi | number | Maximal value |
- Return
- number: Bounded n.
dpi72_to_cm(number n)
Convert a 72 DPI pixel value into centimeters.
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | number | n |
- Return
- number: number
cm_to_dpi72(number n)
Convert a centimeter value into 72 DPI pixels.
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | number | n |
- Return
- number: number
duration_note_to_ms(int noteDuration, number tempo)
Convert a note duration to milliseconds, according to tempo.
| Parameter | Type | Default | Description |
|---|---|---|---|
| noteDuration | int | noteDuration | |
| tempo | number | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| milliseconds | number | milliseconds | |
| tempo | number | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| percent | int | percent | |
| noteDuration | int | noteDuration | |
| tempo | number | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| milliseconds | number | milliseconds | |
| noteDuration | int | noteDuration | |
| tempo | number | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| nbOf256th | int | nbOf256th | |
| tempo | number | 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
| Parameter | Type | Default | Description |
|---|---|---|---|
| milliseconds | number | milliseconds | |
| noteDuration | int | noteDuration | |
| tempo | number | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| nbOf256th | int | nbOf256th | |
| noteDuration | int | noteDuration | |
| tempo | number | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| nbOf256th | int | nbOf256th | |
| noteDuration | int | noteDuration | |
| tempo | number | 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
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| time | int | Symbol.Time, Score.TimeBeginSelection |
- Returns
- number: Tempo value (floatting point number)
- int: Reference note length,
DURATION_QUARTERfor general tempo - Dynamic:
nilif 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
- 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?
| Parameter | Type | Default | Description |
|---|---|---|---|
| dynamic | Dynamic | dynamic |
- Return
- boolean:
trueifdynamic.Type==DYNAMIC_TEMPO
DynamicIsOttava(Dynamic dynamic)
Is dynamic an ottava (8va, 8vb, 15va or 15vb)?
| Parameter | Type | Default | Description |
|---|---|---|---|
| dynamic | Dynamic | dynamic |
- Return
- boolean:
trueif dynamic is 8va, 8vb, 15va or 15vb
DynamicIsPedal(Dynamic dynamic)
Is dynamic an pedal (Ped.
or *)?
| Parameter | Type | Default | Description |
|---|---|---|---|
| dynamic | Dynamic | dynamic |
- Return
- boolean:
trueif dynamic is Ped. or *
DynamicIsVelocity(Dynamic dynamic)
Is dynamic a velocity (power) change?
| Parameter | Type | Default | Description |
|---|---|---|---|
| dynamic | Dynamic | dynamic |
- Return
- boolean:
trueif 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
| Parameter | Type | Default | Description |
|---|---|---|---|
| pitch | int | pitch | |
| preferredAccidental | int | AUTO | Preferred 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. |
| compatible | int | ffalse | If true return value that HA can handle, 11 instead of B-1, a value in bounds. |
| preferredNote | string | "" | English note "A" to "G", if no preferred accidental or AUTO, select the enharmonic from the preferred note. If result is "A" and preferred note is "G" then result will be "G##", unless allowDoubleAccidental is false. |
- Returns
- string: Anglo-saxon note name followed by octave, e.g. "Ab5".
- int: Accidental for the note, one of MSDefine NATURAL,FLAT,SHARP,DOUBLE_FLAT,DOUBLE_SHARP constants.
SMStringToPitch(string name)
Extension and bugfix for builtin StringToPitch function.
Does not handle microtonal accidentals.
- Allow pitches out of 0..127 bounds
StringToPitch("B-1")gives the strange 71 result,SMStringToPitch("B-1")returns 11- Handles double-sharp (## or x) and double-flat (bb)
| Parameter | Type | Default | Description |
|---|---|---|---|
| name | string | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| staff | Staff | staff | |
| held | boolean | nil | Hold chord until next is encountered? If nil, use the chord line setup of the staff. HA needs underscore (_) to hold a chord, but this is unsightly for printing, and works randomly. |
- Return
- table: table
- See
- Chord for more details about Chord object.
- Example
local chords = GetChordsFromStaff(FrontScore(), FrontScore().FirstStaff) for i=1,getn(chords) do print("Chord #" .. i .. ": "..chords[i].Chord:toASCIIName()) print("Bar #" .. chords[i].BarNumber) print(tdebug(chords[i].Chord:notes())) end
GetGlobalSetting(string settingName, boolean multiple)
Reads a line from global settings file, when MyrScript has no built-in function to get the value of a global setting.
| Parameter | Type | Default | Description |
|---|---|---|---|
| settingName | string | settingName | |
| multiple | boolean | false | If false, first line starting with settingName then return it, if true, return all lines that start with settingName in a table. |
- Return
-
- A table if
multiple = true, - A string if
multiple = falseand the setting is found, nilifmultiple = falseand no setting is found.
- A table if
- Example
local tab = GetGlobalSetting("tabPredefNuances", true) --> {"tabPredefNuances 0 20", "tabPredefNuances 1 40", ...} local ppp = GetGlobalSetting("tabPredefNuances 0") --> 20 local pp = GetGlobalSetting("tabPredefNuances 1") --> 40
GetPreferredFont(string object)
Get preferred font from Global settings > Fonts
| Parameter | Type | Default | Description |
|---|---|---|---|
| object | string | 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
nilif not found - int: Face, or
nilif not found - int: Size, or
nilif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| instr | Instrument | instr | |
| excludeMutedStaves | boolean | false |
- Return
- boolean: boolean
SMEnterString(string text, string defaultValue)
Call to EnterString with accessibility and assertions checks
| Parameter | Type | Default | Description |
|---|---|---|---|
| text | string | The prompt text | |
| defaultValue | string | "" | A default value |
- Return
- string: The entered text or
nilif user canceled.
EnterNumber(string text, number defaultValue, number minValue, number maxValue)
Ask the user to enter a number.
Use EnterString(...), and checks that the entered is a number within bounds. In case of error, ask again.
| Parameter | Type | Default | Description |
|---|---|---|---|
| text | string | Text to dispaly in prompt popup | |
| defaultValue | number | nil | A pre-defined value, or nil to force user to enter a value. |
| minValue | number | nil | If specified, entered value is bound by min and max. |
| maxValue | number | nil | If specified, entered value is bound by min and max. |
- Return
- number: or
nilif 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. 
| Parameter | Type | Default | Description |
|---|---|---|---|
| prompt | string | A prompt text above the plotter, nil means no prompt text. | |
| minX | number | 0 | Minimal value for X |
| maxX | number | 0 | Maximal value for X |
| stepX | number | 1 | Step 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. |
| factoryX | number | currentX | Default (factory) value for X, a dual click on the slider goes back to this value |
| currentX | number | factoryX | Current displayed X value |
| minY | number | 0 | Minimal value for Y |
| maxY | number | 0 | Maximal value for Y |
| stepY | number | 1 | Step 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. |
| factoryY | number | currentY | Default (factory) value for Y, a dual click on the slider goes back to this value |
| currentY | number | factoryY | Current displayed Y value |
| displayValuesMask | string | "%x, %y" | Mask for displaying values, %x and %y are replaced by values. |
- Returns
- number: X,
nilif user cancelled the dialog - number: Y,
nilif user cancelled the dialog - Errors
- if minX >= maxX or minY >= maxY
- if factoryX or currentX are outside of [minX:maxX] range
- if factoryY or currentY are outside of [minY:maxY] range
- if factoryX and currentX, or factoryY and currentY are
nil. - Example
-- Create a new document with one staff, go to Page mode. -- This code moves first staff name position -- X between -50 and 50, Y between -30 and 30, steps are 1 -- Negative Y go up, positive Y go down. -- Factory position is 0,0, current is 5,-24 Include "SMUtils" x,y = EnterXY("Test XY", -50, 50, 1, 0, 5, -30, 30, 1, 0, -24, false, true, {FrontScore()}, function(x,y,args) local staff = args[1].FirstStaff staff.TitleXOffset, staff.TitleYOffset = x, y Application.UpdateScores() end, "%x px, %y px" -- not mandatory, just show that unit is pixel (in 72 DPI) )
ChooseNoteHeadShape(int defaultValue)
Open a dialog to choose a note head shape.
| Parameter | Type | Default | Description |
|---|---|---|---|
| defaultValue | int | SHAPE_NORMAL | One of SHAPE_* constants in MSDefine |
- Return
- int: One of SHAPE_* constants, or
nilif user cancelled the choice.
EnsureObjectInStaffArea(Score score, Staff staff, obj)
Ensure an object is in the Staff area, move it vertically if needed.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| staff | Staff | staff | |
| obj | Object: Dynamic, StaffText, FXProcessor, Picture |
- Return
- boolean:
trueif object has been moved vertically,falseotherwise.
CopyOrnaments(Symbol from, Symbol to)
Copy all ornaments from a Symbol to another one.
- Returns
- int: Number of copied ornaments
- int: Number of copy errors
IsThemeSoundsActive()
Are interface sounds active in scripts using SMDialog and SMMenu?
To set up screen reader, go to Scripts > Miscellaneous > Swiss knife menu, then Settings > Interface sounds.
- Return
- boolean:
trueif active,nilorfalseif not set up.
PlayThemeSound(string soundName, boolean wait)
Play a "theme" sound, if set to active.
| Parameter | Type | Default | Description |
|---|---|---|---|
| soundName | string | One of "open", "close", "bell", "error", "confirmation", "message", "toggle-off", "toggle-on", "window-slide" | |
| wait | boolean | false | If true, wait until sound file if played to continue script execution. If false, script continue immediately. A new call to PlayThemeSound(...) or Application.PlayWavFile(...) may interrupt and replace the first played sound. |
IsScreenReaderActive()
Is there a screen reader, a voice that assist visually impaired user?
The screen reader is set up by the script in Miscellaneous > Screen Reader setup. A call to ScreenReader("words to say") wil lsay nothing if not set up, or will say the words if a human voice is choosen.
If the words need time or resource to be build, you can optimize your code by calling IsScreenReaderActive() before this task.
To set up screen reader, go to Scripts > Miscellaneous > Swiss knife menu, then Settings > Accessibility.
- Return
- boolean:
trueif active,nilorfalseif not set up. - See
- ScreenReader
MuteScreenReader(int delay)
Temporarily mute the Screen Reader for a short delay.
It may be useful, for optimization concerns, if next coming actions will call ScreenReader(...) multiple times in a very short delay.
If ScreenReader is not set up to active, then this has no effect.
| Parameter | Type | Default | Description |
|---|---|---|---|
| delay | int | 1000 | Delay, in milliseconds. |
UnMuteScreenReader()
After MuteScreenReader(...) and the massive actions that would have produced unaudible audio messages, unmute the Screen Reader.
If ScreenReader is not set up to active, then this has no effect.
ScreenReader(string text, boolean wait)
Say the text if text to speech is enable for visually impaired people (screen reader).
| Parameter | Type | Default | Description |
|---|---|---|---|
| text | string | text | |
| wait | boolean | false | Wait until the text is fully said |
SMAlert(string msg)
Add accessibility to built-in Alert() function.
| Parameter | Type | Default | Description |
|---|---|---|---|
| msg | string | msg |
SMConfirmation(string msg)
Add accessibility to built-in Confirmation() function.
| Parameter | Type | Default | Description |
|---|---|---|---|
| msg | string | msg |
- Return
- boolean: The same result than
Confirmation(msg)
SMMessage(string msg, boolean skipVisual)
Add accessibility to built-in Message() function.
The Message(...) display msg and requires user to click 'Ok' button or press Enter key. If a screen reader is set (Scripts > Misc. > Swiss knife menu > Settings), msg is said by the TTS. An optional argument allow only vocal message (skip the dialog) if screen reader is active.
| Parameter | Type | Default | Description |
|---|---|---|---|
| msg | string | msg | |
| skipVisual | boolean | false | If screen reader is active, say msg but skip the Message(...) dialog. Visually impaired user will hear the message and won't need to click the 'Ok' button. |
MenuSingleChoice(string title, Lexicon lexicon, datas, string header, boolean hideRadios)
Menu to pick one value in a list of items as radio buttons.

| Parameter | Type | Default | Description |
|---|---|---|---|
| title | string | Menu title | |
| lexicon | Lexicon | 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:
| ||
| header | string | "" | Header question, more visible than window title. Can be styled, multiple lines |
| hideRadios | boolean | false | By default, radio buttons are displayed.
Confirmation(...) where you need more answers than yes/no. |
- Return
- choosen value (or caption), or
nilif user canceled the choice. - See
- https://www.myriad-online.com/cgi-bin/bbs/YaBB.pl?board=MYRSCRIPT;action=display;num=1760458849
- Example
local sd = MenuSingleChoice("Change stems direction", nil, {{"Auto", true, STEM_AUTO, "image:stemupdown.png"}, {"Up", false, STEM_UP, "image:stemup.png"}, {"Down", false, STEM_DOWN, "image:stemdown.png"} }) if sd then -- change the stems direction of symbols -- sd = STEM_AUTO, or STEM_UP, or STEM_DOWN else -- sd=nil, no selection, user canceled the choice end
MenuMultipleChoice(string title, Lexicon lexicon, datas, int minNbOfChoice, int maxNbOfChoice, string header)
Menu to pick multiple value in a list of items as checkboxes.
For example, ChooseStaves(...) call it. 
| Parameter | Type | Default | Description |
|---|---|---|---|
| title | string | Menu title | |
| lexicon | Lexicon | 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:
| ||
| minNbOfChoice | int | 1 | Minimum number of items to choose, 0 means user can select nothing. |
| maxNbOfChoice | int | 0 | Maximum number of items to choose, 0 means no limit. |
| header | string | "" | Header question, more visible than window title. Can be styled, multiple lines |
- Return
- table: Choosen values (or captions), or
nilif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| multiple | boolean | true | true if several staves can be chosen, false if only one staff can be chosen. |
| visibleOnly | boolean | true | true if only visible staves are provided. |
| filterFunc | function | Function that receives Score and Staff arguments, returns true if the staff appears in list, false if not. | |
| selectFunc | function | Function that receives Score and Staff arguments, returns true if the staff is selected by default, false if not selected. | |
| minNbOfChoice | int | 1 | Minimum number of staves to choose, 0 means user can choose no staff. No effect if multiple is false. |
| maxNbOfChoice | int | 0 | Maximum 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
nilif user canceled the choice.
GetStavesGroups(Score score, Staff staff)
Get all StavesGroups of the score or containing staff if this argument is provided.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| staff | Staff | nil | If 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
| Parameter | Type | Default | Description |
|---|---|---|---|
| sg | StavesGroup | sg |
- Return
- table: Array of Staff
GetMergedStaves(Staff staff)
Get all staves merged with staff, included.
If staff is not merged, it returns {staff}, 1, only the argument staff, and 1 is the index of it in the table.
| Parameter | Type | Default | Description |
|---|---|---|---|
| staff | Staff | staff |
- Returns
- table: Table of Staff objects
- int: The index of staff in the table.
StavesGroupName(StavesGroup sg)
Return the name (title) of sg or build a name from its first and last grouped staves.
| Parameter | Type | Default | Description |
|---|---|---|---|
| sg | StavesGroup | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| multiple | boolean | true | true if several staves groups can be chosen, false if only one staves group can be chosen. |
| visibleOnly | boolean | true | true if only visible staves groups are provided. |
| filterFunc | function | Function that receives Score and StavesGroup arguments, returns true if the staves group appears in list, false if not. | |
| selectFunc | function | 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
nilif user canceled the choice.
AdjustStavesGroupSymbolPosition(Score score, table groups)
Experimental: Adjust horizontal and vertical staves group symbole (braces and brackets).
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| groups | table | nil | Table 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.
ChooseView(Score score, boolean index, int (default=current)
Ask the user to choose one view, or a value for ViewIndex.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| index | boolean | Add the choices
| |
| (default=current | int | view) selected index |
- Return
- int: view index
FontFaceNumberToString(int face)
Convert a font face (sum of FACE_* constants from MSDefine) to strings.
| Parameter | Type | Default | Description |
|---|---|---|---|
| face | int | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| str | string | 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.

"Tempo", "Staff name", see GetPreferredFont(..)),
then, a list of favorites fonts,
then, a list of suggested fonts (e.g. found in score).
| Parameter | Type | Default | Description |
|---|---|---|---|
| object | string | 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". | |
| suggestedFonts | table | A table of TextStyle or table {name, face, size[, color]} | |
| selected | A TextStyle or table {name, face, size[, color]} |
- Returns
- string: Font name,
nilif 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(...)
| Parameter | Type | Default | Description |
|---|---|---|---|
| font | string | nil | Default font |
| face | nil | Default face. A number (sum of FACE_* constants) or a string like "BI" for bold italic, second returned value by FontFaceNumberToString(...). | |
| size | number | nil | Default size |
| color | string | nil | Default color in RGB format. |
- Returns
- string: Font name,
nilif 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.

"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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| object | string | The name you want, e.g. "Staff background", "Staff lines"... | |
| suggestedColors | table | nil | A 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
nilif user canceled the choice. - string: Choosen color, in #RRGGBB format, or
nilif user canceled the choice. - int: Color index, or nearest in 256 colors palette, or
nilif user canceled the choice.
AddImagesDirectory(string path)
Add a directory where script can search for pictures.
Menus and other Component may include image (picture) which are searched by file name in some Harmony's subdirs, but not in relative paths from the current script. If you script embed images, it is good practice to call AddImagesDirectory(GetCurrentScript()) just after Include "SMUtils".
| Parameter | Type | Default | Description |
|---|---|---|---|
| path | string | path |
IsPowerOfTwo(number n)
Is n a number power of 2?
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | number | n |
- Return
- boolean:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| set | number | A sum of flags | |
| flag | number | The big to test, a number power of 2. |
- Return
- boolean:
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| set | number | A sum of flags | |
| flag | number | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| set | number | A sum of flags | |
| flag | number | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| t | table | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| barN | int | Bar number, must be lower or equal to Score.NumberOfBars | |
| staffBegin | Staff | nil | If not nil, first or only staff to select, instead of all staves. |
| stafEnd | Staff | nil | If not nil, last staff to select |
- Error
- if
barN > score.NumberOfBarsor staff is notniland 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...
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| setName | string | Setting name, e.g. "conductor", "drums" | |
| full | boolean | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| setName | string | Setting name, e.g. "conductor", "drums" |
- Return
- int: Number of modified settings
CopyFreeObjects(Score src, Score dest)
Copy free objects from one Score to another.
FreeObject visible only on a specific view are copied to the view with the same name, else to all views.
All properties, including tags, are copied.
- 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| batchName | string | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| batchName | string | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| batchName | string | Batch name, by convention the type of object function will accept as argument ("Score", "Staff"...). |
- Return
- bvool
trueif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| batchName | string | Batch name, by convention the type of object function will accept as argument ("Score", "Staff"...). | |
| label | string | Just a label to show progression or report an error with context. | |
| func | function | The function that will be performed later, by BatchExecute.
|
BatchClear(string batchName)
Clear the batch stack, in case of cancellation or when all calls are done.
| Parameter | Type | Default | Description |
|---|---|---|---|
| batchName | string | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| batchName | string | Batch name, by convention the type of object function will accept as argument ("Score", "Staff"...). | |
| score | Score | If needed, the score on which the batch will be processed | |
| object | nil | The object (Staff, Instrument...) that will be given as first argument to each function in the stack. |
- Return
- int: Number of functions called.
DeleteDisabledCurves(Staff staff)
Remove the parameter curves that have been disabled.
| Parameter | Type | Default | Description |
|---|---|---|---|
| staff | Staff | staff |
- Return
- int: Number of deleted curves
DeleteEmptyCurves(Staff staff)
Remove the empty parameter curves when they have no values.
| Parameter | Type | Default | Description |
|---|---|---|---|
| staff | Staff | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score |
Serialize(obj)
Serialize an object to store it as string and later deserialization.
| Parameter | Type | Default | Description |
|---|---|---|---|
| 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| str | string | str |
- Return
- Copy of previously serialized object
StorageAreaClear(StorageArea storage, string tag4)
Remove all items from the StorageArea storage for tag tag4.
| Parameter | Type | Default | Description |
|---|---|---|---|
| storage | StorageArea | Application.StorageArea, myScore.StorageArea... | |
| tag4 | string | 4-char tag |
- Return
- int: Number of deleted items
DeleteAllFreeObjects(Score score)
Delete all free objects from a score, without confirmation.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | 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."
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| prompt | string | "Select a rehearsal mark" | Title of the menu. |
| selectedBar | int | 0 | Preselect target from the bar number selectedBar:
|
| selectedName | string | nil | Select the target which displayed name is selectedName. nil means no selection from the target displayed name. |
- Return
- Target: Selected target or
nilif 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| target | Target | nil | nil for all targets of score |
| visible | boolean | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| staff | Staff | staff |
- Return
- int: Number of deleted clefs.
ShowHiddenClefs(Staff staff)
Show hidden clefs where needed.
After PDF or MusicXML import, if a staff is invisible on first page, first clef is hidden.
| Parameter | Type | Default | Description |
|---|---|---|---|
| staff | Staff | staff |
- Return
- int: Number of shown clefs.
MidiGetEventFiltered(boolean allowNoteOn, boolean allowNoteOff, boolean allowCC, boolean allowProgramChange, boolean allowAftertouch, boolean allowPitchBend, boolean allowOthers, int delay, table allowedSources)
Apply a filter to Midi.GetEvent to exclude some Midi messages and return all events since last call.
You can exclude:
- message you don't need, e.g. aftertouch
- 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| allowNoteOn | boolean | true | Allow Note On events? |
| allowNoteOff | boolean | true | Allow Note Off events? |
| allowCC | boolean | true | Allow controller change events? |
| allowProgramChange | boolean | true | Allow PC event? |
| allowAftertouch | boolean | true | Allow aftertouch event? |
| allowPitchBend | boolean | true | Allow pitch bend event? |
| allowOthers | boolean | true | Allow other events? |
| delay | int | 0 | Delay 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. |
| allowedSources | table | nil | The accepted sources (nil means all - no filter):
|
- 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
- Event, int: type of event :
MidiSendCC(int interface, int channel, int controller, int value)
Send a control change (CC) message to a MIDI device.
| Parameter | Type | Default | Description |
|---|---|---|---|
| interface | int | 1-based to match the numbering in hardware configuration (1-12) | |
| channel | int | 1-based to match the usual chanel numbering (1-16) | |
| controller | int | 0 for bank select, 1 for modulation wheel, 2 for breath control... See https://anotherproducer.com/online-tools-for-musicians/midi-cc-list/ | |
| value | int | between 0 and 127 |
- Example
function findTeensy() for i=1,12 do local name = Midi.OutGetName(i) if name == "Teensy MIDI" then return i; end end end Midi.OutBegin("Teensy MIDI") MidiSendCC(port, 1, 90, 50) Midi.OutEnd()
ElementsToTable(...)
Transforme a list (multiple returned values from a function call) to a table.
| Parameter | Type | Default | Description |
|---|---|---|---|
| ... | List of elements |
- Return
- table: Table containing all elements.
- See
- TableToElements
- Examples
print(strfind("abcd", "b", 1, true)) --> 2 2 local pos = strfind("abcd", "b", 1, true) --> 2, one data lost local t = ElementsToTable(strfind("abcd", "b", 1, true)) --> {2, 2}
-- Symbol.GetSlurSettings returns variable number of vallues, -- symbol.SetSlurSettings accept variable number of arguments -- Here is a "hack" to change slur settings safely. local ss = ElementsToTable(symbol.GetSlurSettings()) ss[1] = SLIDE_SMOOTH ss[12] = true -- automatic computing symbol.SetSlurSettings(TableToElements(ss))
TableToElements(table t)
Bugfix version of MSLibrary's PushAllTableElts(t), return all elements of a table as multiple return values.
PushAllTableElts(...) doesn't hnandle string nor complex objects, this version does.
| Parameter | Type | Default | Description |
|---|---|---|---|
| t | table | If table is indexed as t = {1, "b", 3} then values are returned in their order. Else if table is made of pairs variable to value like in t = {A=1, B="b", C=3} order is not guaranteed. |
- Return
- All values of the table
- Error
- if not enough free stack / too big table
- See
- ElementsToTable
- Examples
local t = {1, "b", 3, FrontScore()} print(TableToElements(t)) --> 1 b 3 userdata(...) -- PushAllTableElts(t) returns 1 nil 3 and crashes
-- Symbol.GetSlurSettings returns variable number of vallues, -- symbol.SetSlurSettings accept variable number of arguments -- Here is a "hack" to change slur settings safely. local ss = ElementsToTable(symbol.GetSlurSettings()) ss[1] = SLIDE_SMOOTH ss[12] = true -- automatic computing symbol.SetSlurSettings(TableToElements(ss))
CopyBarNumberings(Staff source, Staff dest)
Copy bar numberings settings from one staff to another.
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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| firstBar | int | 1 | |
| lastBar | int | score.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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| firstBar | int | 1 | First bar where %2 and %4 are searched |
| lastBar | int | score.NumberOfBars | Last 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| grdm | int |
|
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
| Parameter | Type | Default | Description |
|---|---|---|---|
| s | string | s | |
| signed | boolean | false | Signed 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| s | string | s | |
| signed | boolean | false | Signed 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
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | int | Positive, 0 or negative. | |
| size | int | 1 | Pad result with zeros to ensure result string length is a multiple of size |
| separator | string | "" | 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)
| Parameter | Type | Default | Description |
|---|---|---|---|
| n | int | n | |
| size | int | 1 | Pad result with zeros to ensure result string length is a multiple of size |
| separator | string | "" | 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!
| Parameter | Type | Default | Description |
|---|---|---|---|
| a | int | a | |
| bits | int | 32 |
- Return
- int: int
- Example
local a = 5 -- 0101 print(bit_not(a, 4)) --> 10 (1010)
SMFirstSelectedSymbol(Score score, Staff staff, boolean ignoreGhostRest)
Returns the first selected symbol (range or individual selection) of the staff or the whole score.
This function is more accurate than Staff.FirstSelectedSymbol, handles individual selection, and the 3rd argument allows you to ignore ghost rests.
Note: like Staff.FirstSelectedSymbol, the returned symbol may not be included in actions applied to selection (in Edit menu). If the range selection is after the note head but before next note, it is considered as selected by MyrScript, whereas actions in Edit menu won't apply to it.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| staff | Staff | If nil, look for selected symbol on all staves and return the one that begins the first (least symbol.Time) | |
| ignoreGhostRest | boolean | If first selected symbol is a ghost rest, go forward until another kind of symbol is found |
- Return
- Symbol: or
nilif selection contains no symbol
SMLastSelectedSymbol(Score score, Staff staff, boolean ignoreGhostRest)
Returns the last selected symbol (range or individual selection) of the staff or the whole score.
This function is more accurate than Staff.LastSelectedSymbol, handles individual selection, and the 3rd argument allows you to ignore ghost rests.
Note: like Staff.LastSelectedSymbol, the returned symbol may not be included in actions applied to selection (in Edit menu). If the range selection is after the note head but before next note, it is considered as selected by MyrScript, whereas actions in Edit menu won't apply to it.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| staff | Staff | If nil, look for selected symbol on all staves and return the one that ends the last (greatest symbol.Time + symbol.Duration) | |
| ignoreGhostRest | boolean | If last selected symbol is a ghost rest, go backward until another kind of symbol is found |
- Return
- Symbol: or
nilif selection contains no symbol
SearchNextSymbol(Score score, staves, from, function matcher)
Search next symbol with custom matcher function, in whole score or a list of staves, at a time position or after a symbol.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| staves | nil | ||
| from | 0 |
| |
| matcher | function | nil | A function that accepts a Symbol argument and returns true if the symbol matches the criteria(s) of the search. If matcher is nil then return the next symbol which is not a ghost rest. |
- Returns
- Symbol: First matching symbol at time from or after from symbol,
nilif not found (end of music is reached) - Staff: The staff containing the returned symbol, or
nilif not found - Example
local m = function(sym) return sym.IsRest; end local rest, staff = SearchNextSymbol(FrontScore(), nil, 0, m) local cpt = 0 while rest do cpt = cpt + 1 print("#"..cpt, "staff #"..staff.Index, "time="..rest.Time) rest, staff = SearchNextSymbol(FrontScore(), nil, rest, m) end
SearchPreviousSymbol(Score score, staves, from, function matcher)
Search previous symbol with custom matcher function, in whole score or a list of staves, at a time position or before a symbol.
| Parameter | Type | Default | Description |
|---|---|---|---|
| score | Score | score | |
| staves | nil | ||
| from | music duration |
| |
| matcher | function | nil | A function that accepts a Symbol argument and returns true if the symbol matches the criteria(s) of the search. If matcher is nil then return the previous symbol which is not a ghost rest. |
- Returns
- Symbol: First matching symbol at time from or before from symbol,
nilif not found (start of music is reached) - Staff: The staff containing the returned symbol, or
nilif not found - Example
local m = function(sym) return sym.IsRest; end local rest, staff = SearchPreviousSymbol(FrontScore(), nil, nil, m) local cpt = 0 while rest do cpt = cpt + 1 print("#"..cpt, "staff #"..staff.Index, "time="..rest.Time) rest, staff = SearchPreviousSymbol(FrontScore(), nil, rest, m) end
GetKeySignatureAtBar(Staff staff, int barN, boolean visibleOnly)
Get the key signature at requested bar of requested staff.
Search for last BarSetting less or equal to barN and retrieve its KeySignature. If visibleOnly is true then go backward until a visible key signature is found.
| Parameter | Type | Default | Description |
|---|---|---|---|
| staff | Staff | staff | |
| barN | int | barN | |
| visibleOnly | boolean | false | If true, retrieve the last visible key signature. Else it can retrieve a hidden key signature. |
- Return
- KeySignature:
nilpossible if no visible key signature and visibleOnly istrue.
longest_common_subsequence(a, b)
Longest Common Subsequence (LCS) algorithm, basis for data comparison.
This compares 2 strings or tables (of numbers or strings) and returns a string or a table containing common chars or items.
For the two strings "ABC" and "ACE", the LCS is "AC".
| Parameter | Type | Default | Description |
|---|---|---|---|
| a | First string or table (of comparable elements) | ||
| b | Second string or table (of comparable elements) |
- Return
- A string if a and b are strings, else a table.
- Error
- if
type(a) ~= type(b) - See
- CompareTextFiles
- CompareTables
- CompareStrings
- https://en.wikipedia.org/wiki/Longest_common_subsequence
- https://www.geeksforgeeks.org/dsa/longest-common-subsequence-dp-4/
CompareTables(table lines1, table lines2)
Compare two tables, returns a diff-like format.
The diff format is used for data comparison, or, in development environnement, to compare old and new lines of source code.
tables in arguments must contain comparable (==) and tostring()able items: so it's restricted to numbers and strings. For complex datas, consider serialization.
| Parameter | Type | Default | Description |
|---|---|---|---|
| lines1 | table | First (oldest) table of strings | |
| lines2 | table | Second (newest) table of strings |
- Returns
- table: Lines in approximate diff format:
- Added lines start with a + (plus)
- Removed lines start with a - (minus)
- Common lines (unchanged) start with a space.
- int: Number of added lines
- int: Number of removed lines
- int: Number of unchanged lines
- See
- CompareTextFiles
- CompareStrings
table_unique(table tab)
Remove duplicates from a table
| Parameter | Type | Default | Description |
|---|---|---|---|
| tab | table | tab |
- Return
- table: table
RecentScriptsAdd(string path, string name)
In debug mode, add current script to the "Recent scripts" list.
This is a tool for devs that allow them to quickly run or edit most recents scripts, from Scripts > Miscellaneous > Dev tools > Recents scripts
| Parameter | Type | Default | Description |
|---|---|---|---|
| path | string | GetCurrentPath( | ) Directory where the script is stored |
| name | string | Application.CurrentScriptName | Script file name |
- Usage
-- At the beginning of your script Include "SMUtils" RecentScriptsAdd() -- Run at least once your script from the editor (in debug mode)
SymbolGetAccidental(Symbol sym)
Return accidental data for a Symbol, handles microtonals.
Return nil if sym is not a note.
| Parameter | Type | Default | Description |
|---|---|---|---|
| sym | Symbol | sym |
- Returns
- int: Accidental constant from MSDefine (except AUTO). If the value is greater or equal than 1000, it is a microtonal accidental, see ORNAMENT_MA_* constants.
- int: Accidental value in 100th of semitone.
- boolean:
trueif accidental is visible,falseif invisible - boolean:
trueif accidental is cautionary,falseif essential. This may betrueeven if invisible, meaning that deleting this accidental will not change the note pitch. - string: Source of the accidental: "note", "bar" (previous note in the bar), "key" (key signature).
SymbolSetAccidentalVisibility(Symbol sym, boolean visible)
Change the accidental visibility of a Symbol.
Handles microtonal accidentals.
| Parameter | Type | Default | Description |
|---|---|---|---|
| sym | Symbol | sym | |
| visible | boolean | true to display accidental, false to hide or delete |
- Return
- boolean:
trueif changes were applied,falseif not,nilif sym is not a note.
SymbolIsMicrotonalAccidental(Symbol sym)
Is the note played with a microtonal accidental?
| Parameter | Type | Default | Description |
|---|---|---|---|
| sym | Symbol | sym |
- Return
- boolean:
trueif sym or a previous note in the same bar has one Ornament of a microtonal accidental, or if the lastspecify a microtonal accidental for that note.
SymbolIsTieVisible(Symbol note)
Is the note tied?
A tie is a kind of "slur" joining two notes head. In Harmony, it is considered as a single note with a split duration.
Two rests may be "tied", without curve, this function ignore rests.
| Parameter | Type | Default | Description |
|---|---|---|---|
| note | Symbol | note |
- Return
- boolean:
trueif note is tied with next note. - See
- Symbol Symbol.GetTiedElements(...)
SymbolsAreContiguous(Symbol a, Symbol b)
Tell if two Symbols are contiguous.
Both can be in chord, this can produce a.Next ~= b.
If both are quarters, and while a is played, 2 eights are also played, then b is considered as contiguous. If both have same pitch, a and b can be tied..
Another way to say: a.Time + a.Duration == b.Time and both are on the same staff.
- Return
- boolean:
trueif a and b are contiguous - See
- SymbolsCanBeTied
SymbolsCanBeTied(Symbol ...)
Symbols can be tied if they are all contiguous and have same played and displayed pitch.
| Parameter | Type | Default | Description |
|---|---|---|---|
| ... | Symbol | A table of Symbols or multiple Symbol arguments. They must be ordered by their time, from first to last. |
- Return
- boolean:
trueif a tie can join ALL notes in argument
SetSlurDirection(Symbol note, boolean isUp)
Set slur direction up or down.
The slur is set to be adjusted automatically.
| Parameter | Type | Default | Description |
|---|---|---|---|
| note | Symbol | The note that starts the slur (the SlurSource). If it ends a slur and doesn't start another one, then the slur settings are set to source note. To avoid confusion, prefer passing the source note as argument. | |
| isUp | boolean | true for up, false for down |
- Return
- boolean:
trueif the slur has been modified
SymbolIsDotted(Symbol sym)
Tell if the Symbol is displayed with dot(s).
If sym is tied (sym.SplitDuration ~= 0), then returns true if at least one of the tied notes is dotted.
-- If sym has a slur instead of a tie, only sym is checked, as the slur target is another Symbol.
| Parameter | Type | Default | Description |
|---|---|---|---|
| sym | Symbol | sym |
- Return
- boolean:
trueif sym requires dot(s) to display its duration on the score.
GetSymbolsInChord(Symbol sym)
Return all symbols in chord with sym (included), in its staff and merged ones.
Symbols are sorted by staff index, then their internal order (generally from higher to lower). This is not guaranteed that symbols are all ordered from higher to lower. Rests are included.
| Parameter | Type | Default | Description |
|---|---|---|---|
| sym | Symbol | sym |
- Returns
- table: Table of Symbol in chord with sym
- int: Index of sym in the table.
- See
- GetOverlappingSymbols
GetOverlappingSymbols(Symbol sym)
Get all symbols (notes and rests) from merged staves, which begin time is before sym end time, and end time is after sym begin time.
This means: if sym is a "drone" note in first merged staff, this will return the drone + the melody in the second merged staff.

If the drone is a serie of notes linked by a slur, then the function must be called for each note of the serie.
If all notes of the drone are tied, it's considered as only one note.
This function may help analysis algorithm, as well as for ties/slurs/stems direction calculation.
There is no guarantee of sorted results: it will be mostly sorted by staff index, time, higher to lower in chord.
| Parameter | Type | Default | Description |
|---|---|---|---|
| sym | Symbol | sym |
- Returns
- table: Table of Symbol which playing time and duration overlap sym playing time.
- int: Index of sym in the table.
- See
- GetSymbolsInChord
CompareSymbolsByPitch(Symbol a, Symbol b)
Compare two Symbols by pitch, then displayed height.
- Return
- int:
- Negative number if a is lower than b,
- Positive if a is higher than b,
- Zero if a and b have same pitch and displayed height.
LinearScaling(number x, number a, number b, number c, number d)
Linear scaling (or linear transformation) of \(x\) from range \([a,b]\) to \([c,d]\).
Use case: convert a MIDI value between 0 and 127 to a number between 0% and 100%.
| Parameter | Type | Default | Description |
|---|---|---|---|
| x | number | x | |
| a | number | a | |
| b | number | b | |
| c | number | c | |
| d | number | d |
- Return
- number: \[ c + \frac{(d - c)(x - a)}{b - a} \]
- Error
- if \(a > b\), or \(c > d\), or \(x\) not in range \([a,b]\).
QuadraticScaling(number x, number a, number b, number c, number d)
Quadratic scaling of \(x\) from range \([a,b]\) to \([c,d]\).
Low values of \(x\) are compressed, high values are expanded.
Use case: a knob or cursor for reverb duration between 0 and 5 s. We need a more precise short duration (0.1 s, 0.3 s) than a longer one (no big difference between 4.5 s and 4.7 s).
| Parameter | Type | Default | Description |
|---|---|---|---|
| x | number | x | |
| a | number | a | |
| b | number | b | |
| c | number | c | |
| d | number | d |
- Return
- number: \[ c + (d - c) \left(\frac{x - a}{b - a}\right)^2 \]
- Error
- if \(a > b\), or \(c > d\), or \(x\) not in range \([a,b]\).
- See
- SquareRootScaling
- PowerScaling
SquareRootScaling(number x, number a, number b, number c, number d)
Square root scaling of \(x\) from range \([a,b]\) to \([c,d]\).
Inverse of QuadraticScaling, high values of \(x\) are compressed, low values are expanded.
| Parameter | Type | Default | Description |
|---|---|---|---|
| x | number | x | |
| a | number | a | |
| b | number | b | |
| c | number | c | |
| d | number | d |
- Return
- number: \[ c + (d - c) \cdot \sqrt{\frac{x - a}{b - a}} \]
- Error
- if \(a > b\), or \(c > d\), or \(x\) not in range \([a,b]\).
- See
- QuadraticScaling
- PowerScaling
PowerScaling(number x, number n, number a, number b, number c, number d)
Power scaling of \(x\) from range \([a,b]\) to \(x^n\) in \([c,d]\).
Flexible control of the non-linearity. QuadraticScaling use \(x^2\), here we add \(n\) argument:
- if \(n > 1\), low values are compressed, high values are expanded,
- if \(0 < n < 1\) low values are expanded, high values are compressed,
- if \(n = 1\) the scaling is linear.
| Parameter | Type | Default | Description |
|---|---|---|---|
| x | number | x | |
| n | number | Power, positive number | |
| a | number | a | |
| b | number | b | |
| c | number | c | |
| d | number | d |
- Return
- number: \[ c + (d - c) \cdot \left(\frac{x - a}{b - a}\right)^n \]
- Error
- if \(n \leq 0\), or \(a > b\), or \(c > d\), or \(x\) not in range \([a,b]\).