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:
- SMJavaCollections
- SMLexicon
- SMLogger
- SMStrings
- SMTheory
- Sylvain Machefert
Classes
Class | Summary |
---|---|
INI | Rough INI configuration file reader and writer. |
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. |
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 |
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. |
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. |
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? |
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. |
table | FileReadLines(string path, int stringEncoding, int crlf, boolean errorIfNotFound) Syntaxic sugar to read all lines of a file, and return a table of them. |
FileWriteLines(string path, table lines, function formatFunc, int stringEncoding, int crlf) Syntaxic sugar to writes a table of strings as lines in a file. | |
string, 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. |
table | GetFilesInFolder(string folder, string mask, boolean recursive, boolean fullPath)BrowseFolder(...) needs a callback function, and has a bug: here is a fixed and simplified version. |
string | GetGlobalSetting(string settingName) Reads a line from global settings file, when MyrScript has no built-in function to get the value of a global setting. |
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 |
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? |
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 . | |
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) Menu to pick multiple value in a list of items as checkboxes. |
MenuSingleChoice(string title, Lexicon lexicon, datas) Menu to pick one value in a list of items as radio buttons. | |
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. | |
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() . | |
SMAlert(string msg) Add accessibility to built-in Alert() function. | |
int | SMApplyToAllSelectedSymbols(Score score, function processFunc) Apply a function to all selected symbols, individually selected or continous selection. |
int | SMApplyToAllSymbols(Score score, Staff staff, int firstBar, int lastBar, function processFunc) Apply a function to all symbols in the score, or staff, or in a rang eof bars. |
boolean | SMConfirmation(string msg) Add accessibility to built-in Confirmation() function. |
SMMessage(string msg) 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) Say the text if text to speech is enable for visually impaired people (screen reader). | |
string | ScriptReadVersion(string file) Read the version of a script. |
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 | SortTargets(Score score) Sort the targets (rehearsal marks) by bar number. |
StaffSetAmbitus(Score score, Staff staff, boolean state) Set the ambitus enabled or disabled for staff, and also at score's level else ambitus won't display. | |
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. |
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. |
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 | 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. |
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. | |
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will stop with a console error message. - See
- assertPositiveNumber
- assertNegativeNumber
- assertNotZero
assertPositiveNumber(n, string errorMessage, boolean visual)
Assert n is a positive number, else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - See
- assertNumber
- assertNegativeNumber
- assertNotZero
assertNegativeNumber(n, string errorMessage, boolean visual)
Assert n is a negative number, else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - See
- assertNumber
- assertPositiveNumber
- assertNotZero
assertNotZero(n, string errorMessage, boolean visual)
Assert n is a number but not 0
, else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - See
- assertNumber
- assertPositiveNumber
- assertNegativeNumber
assertString(s, string errorMessage, boolean visual)
Assert s is a not-nil string (possibly empty), else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - See
- assertNotEmptyString
assertNotEmptyString(s, string errorMessage, boolean visual)
Assert s is a not-nil and not empty string, else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - See
- assertString
assertBoolean(b, string errorMessage, boolean visual)
Assert b is a boolean (true
or false
, not nil
), else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - See
- assertTrue
- assertFalse
- assertExpression
assertTrue(b, string errorMessage, boolean visual)
Assert b is true
, else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - See
- assertFalse
- assertNotNil
- assertExpression
assertFalse(b, string errorMessage, boolean visual)
Assert b is false
, else throw errorMessage.
Note: if you check a expression, e.g. x < y
, Lua returns nil
if the comparaison fails, instead of false
.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - See
- assertTrue
- assertNil
- assertExpression
assertTable(t, string errorMessage, boolean visual)
Assert t is a table, else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
assertFunction(f, string errorMessage, boolean visual)
Assert f is a function, else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
assertNil(n, string errorMessage, boolean visual)
Assert n is nil
, else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - See
- assertNotNil
- assertFalse
- assertExpression
assertNotNil(n, string errorMessage, boolean visual)
Assert n is not nil
, else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - See
- assertNil
- assertTrue
- assertExpression
assertExpression(expr, string errorMessage, boolean visual)
Assert an expression result is true.
This is the equivalent of Lua assert
function with more logging.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - See
- assertTrue
- assertNotNil
assertEquals(expr, expected, string Text, boolean visual)
Assertion an expression or function call equals an expected result.
This is useful for unit tests.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - Error
- If expr ~= expected
assertInArray(value, table t, string text, boolean visual)
Assert a value is found in a table.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - Error
- If value not found in t
assertDialog(dialog, string errorMessage, boolean visual)
Assert dialog is a Dialog, else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
assertScore(s, string errorMessage, boolean visual)
Assert s is a Score, else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error.
assertType(t, string expectedType, string errorMessage, boolean visual)
Assert type(t)
is a expectedType, else throw errorMessage.
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:
true
if assertion is correct,nil
(for false) if it failed. If visual ~= true, no need to check the returned value, script will die with a console error. - See
- assertDialog
- assertFunction
- assertNumber
- assertScore
- assertString
- assertTable
- Example
assertType(s, "Staff", "MyFunction, argument #1") --> if s is not a Staff, this print --> ERROR MyFunction, argument #1, expected Staff, got ...
bool(expr)
Converts expr to a boolean.
Parameter | Type | Default | Description |
---|---|---|---|
expr | expr |
- Return
- boolean:
true
if expr is true,false
otherwise.
NOT(boolean b)
NOT function in boolean algebra.
Lua not x
means "not nil", so not true
is always true
. NOT(true)
returns nil
(for false) so it can be used safely in if..then statements. If you want to obtain a real false
, use the bool() function: a = bool(NOT(<expression>))
Parameter | Type | Default | Description |
---|---|---|---|
b | boolean | b |
- Return
- boolean:
true
ifb==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:
true
if all arguments aretrue
nil
(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:
true
if at least one argument istrue
nil
(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:
true
if 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:
true
if 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:
true
if 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:
true
if 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:
true
if 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:
true
if the list contains term,nil
(for false) if the list doesn't contains term - See
- ArrayContains
CompareMyrScriptVersion(string version)
Is MyrScript =, < or > version x.y.z?
As Application.MyrScriptVersion
is a string, comparison may fail in the future, "10.1.1" is greater than "9.9.9" but string comparison will stay it's lower (because "1" < "9").
Parameter | Type | Default | Description |
---|---|---|---|
version | string | Version to compare, in x.y.z form (e.g.: "1.6.9") |
- Return
- string:
"<", ">"
or"="
ifApplication.MyrScriptVersion
is lower, greater or equal to version.
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") --> ">"
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,
nil
if not found. - Example
local c = Collection:new("string") print(gettagname(c)) --> "Collection" print(gettagname("Hello world")) --> "string" print(gettagname(FrontScore().FirstStaff)) --> Staff
IsLuaClass(string className)
Is className the name of a class?
Class is a table with a tag, and a :new(...) method.
Symbol, Staff or Score are not Lua class, Interval, Collection and SMDialog are.
Parameter | Type | Default | Description |
---|---|---|---|
className | string | className |
- Return
- boolean:
true
if it's a class,nil
for false if not. - Example
print(IsLuaClass("table")) --> nil print(IsLuaClass("Collection")) --> 1
tdebug(...)
Return the structure of a table, Collection or Map for debugging to the console.
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)
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.
Parameter | Type | Default | Description |
---|---|---|---|
score | Score | score | |
processFunc | function | Function with a singl Symbol argument, and returns true if symbol has been processed. |
- Return
- int: Number of processed symbols
- Error
- if score is not a Score or processFunc is not a function.
- See
- SMApplyToAllSymbols
SMApplyToAllSymbols(Score score, Staff staff, int firstBar, int lastBar, function processFunc)
Apply a function to all symbols in the score, or staff, or in a rang eof bars.
Parameter | Type | Default | Description |
---|---|---|---|
score | Score | score | |
staff | Staff | nil | nil menas all staves. |
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 a singl Symbol argument, and returns true if symbol has been processed. |
- Return
- int: Number of processed symbols
- Error
- if arguments have wrong types.
- See
- SMApplyToAllSelectedSymbols
PlayNote(Symbol symbol)
Plays a note, shortcut and fix for Staff.PlayNotes()
.
Play only one note (the symbol parameter), in its context (tempo at its Time position), duration, velocity and pitch. Fix the no-sound bug when pitch==0 on grid drum staves.
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_QUARTER
for general tempo - Dynamic:
nil
if no tempo was added to the score, i.e. the returned value is general tempo - Error
- if score is nil
GetDynamicsThatApplyToStaff(Score score, Staff staff)
Get all Dynamic that apply to the specified Staff.
Dynamics are:
- velocity changes (crescendo, decrescendo, pppp to fff)
- Tempo change
- Pedal on/off
- Ottava
- 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:
true
ifdynamic.Type==DYNAMIC_TEMPO
DynamicIsOttava(Dynamic dynamic)
Is dynamic an ottava (8va, 8vb, 15va or 15vb)?
Parameter | Type | Default | Description |
---|---|---|---|
dynamic | Dynamic | dynamic |
- Return
- boolean:
true
if 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:
true
if dynamic is Ped. or *
DynamicIsVelocity(Dynamic dynamic)
Is dynamic a velocity (power) change?
Parameter | Type | Default | Description |
---|---|---|---|
dynamic | Dynamic | dynamic |
- Return
- boolean:
true
if dynamic is crescendo, decrescendo, ppp to fff... i.e. not a pedal, not a tempo, not a ottava
SMPitchToString(int pitch, int preferredAccidental, int compatible, string preferredNote)
Extension and bugfix for builtin PitchToString function.
- Allow pitches out of 0..127 bounds, but keep in mind that HA can't handle them!
PitchToString(11)
gives 11,SMPitchToString(11)
returns B-1
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.
- 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)
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 |
- Return
- string: Found value, or
nil
if not found.
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
nil
if not found - int: Face, or
nil
if not found - int: Size, or
nil
if not found - string: color in RGB format,
"000000"
for now as it may be impossible to parse.
InstrumentIsUsed(Score score, Instrument instr, boolean excludeMutedStaves)
Is instr Instrument used in score ?
Instument.IsUsed
returns true even if applide to rule that is never used, or used by a staff that has Virtual Singer voice active. This function handles these cases.
Parameter | Type | Default | Description |
---|---|---|---|
score | Score | score | |
instr | Instrument | instr | |
excludeMutedStaves | boolean | false |
- Return
- boolean: boolean
EnterNumber(string text, number defaultValue, number minValue, number maxValue)
Ask the user to enter a number.
Use EnterString(...)
, and checks that the entered is a number within bounds. In case of error, ask again.
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
nil
if user cancelled the choice.
EnterXY(string prompt, number minX, number maxX, number stepX, number factoryX, number currentX, number minY, number maxY, number stepY, number factoryY, number currentY, string displayValuesMask)
Ask to enter X,Y coordinates in a plotter with X and Y axis.
It's handy when you ask for 2 values, as X and Y offsets.
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,
nil
if user cancelled the dialog - number: Y,
nil
if user cancelled the dialog - Errors
- if minX >= maxX or minY >= maxY
- if factoryX or currentX are outside of [minX:maxX] range
- if factoryY or currentY are outside of [minY:maxY] range
- if factoryX and currentX, or factoryY and currentY are
nil
. - Example
-- Create a new document with one staff, go to Page mode. -- This code moves first staff name position -- X between -50 and 50, Y between -30 and 30, steps are 1 -- Negative Y go up, positive Y go down. -- Factory position is 0,0, current is 5,-24 Include "SMUtils" x,y = EnterXY("Test XY", -50, 50, 1, 0, 5, -30, 30, 1, 0, -24, false, true, {FrontScore()}, function(x,y,args) local staff = args[1].FirstStaff staff.TitleXOffset, staff.TitleYOffset = x, y Application.UpdateScores() end, "%x px, %y px" -- not mandatory, just show that unit is pixel (in 72 DPI) )
EnsureObjectInStaffArea(Score score, Staff staff, obj)
Ensure an object is in the Staff area, move it vertically if needed.
Parameter | Type | Default | Description |
---|---|---|---|
score | Score | score | |
staff | Staff | staff | |
obj | Object: Dynamic, StaffText, FXProcessor, Picture |
- Return
- boolean:
true
if object has been moved vertically,false
otherwise.
CopyOrnaments(Symbol from, Symbol to)
Copy all ornaments from a Symbol to another one.
- Returns
- int: Number of copied ornaments
- int: Number of copy errors
IsScreenReaderActive()
Is there a screen reader, a voice that assist visually impaired user?
The screen reader is set up by the script in Miscellaneous > Screen Reader setup. A call to ScreenReader("words to say")
wil lsay nothing if not set up, or will say the words if a human voice is choosen.
If the words need time or resource to be build, you can optimize your code by calling IsScreenReaderActive()
before this task.
- Return
- boolean:
true
if active,nil
orfalse
if not set up. - See
- ScreenReader
ScreenReader(string text)
Say the text if text to speech is enable for visually impaired people (screen reader).
Parameter | Type | Default | Description |
---|---|---|---|
text | string | text |
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)
Add accessibility to built-in Message()
function.
Parameter | Type | Default | Description |
---|---|---|---|
msg | string | msg |
MenuSingleChoice(string title, Lexicon lexicon, datas)
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:
|
- Return
- choosen value (or caption), or
nil
if user canceled the choice. - Example
local sd = MenuSingleChoice("Change stems direction", nil, {{"Auto", true, STEM_AUTO, "image:stemupdown.png"}, {"Up", false, STEM_UP, "image:stemup.png"}, {"Down", false, STEM_DOWN, "image:stemdown.png"} }) if sd then -- change the stems direction of symbols else -- no selection, user canceled the choice end
MenuMultipleChoice(string title, Lexicon lexicon, datas, int minNbOfChoice, int maxNbOfChoice)
Menu to pick multiple value in a list of items as checkboxes.
For example, ChooseStaves(...)
call it.
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. |
- Return
- table: Choosen values (or captions), or
nil
if user canceled the choice.
ChooseStaves(Score score, boolean multiple, boolean visibleOnly, function filterFunc, function selectFunc, int minNbOfChoice, int maxNbOfChoice)
Ask the user to choose one or multiple staves.
The builtin Score.UserChooseStaves(...)
is a bit less flexible and not 100% browsable with keyboard. This custom version allow shortcuts, from 1 to 9 for 9 first staves, then the first available letter.
Here is what it looks like: ChooseStaves(...)
displays a menu with checkboxes.
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
nil
if user canceled the choice.
GetStavesGroups(Score score, Staff staff)
Get all StavesGroups of the score or containing staff if this argument is provided.
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
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
nil
if 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,
nil
if user canceled the choice. - int: Font face, sum of FACE_* constants in MSDefine
- int: Size
- string: RGB color
EnterFont(string font, face, number size, string color)
Ask the user to choose font, face, size and color using the built-in EditTextStyle()
dialog.
EnterFont(...)
calls EditTextStyle(...)
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,
nil
if user canceled the choice. - int: Font face, sum of FACE_* constants in MSDefine
- int: Size
- string: RGB color
ChooseColor(string object, table suggestedColors, selected)
Ask the user to choose one color in a menu.
"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
nil
if user canceled the choice. - string: Choosen color, in #RRGGBB format, or
nil
if user canceled the choice. - int: Color index, or nearest in 256 colors palette, or
nil
if user canceled the choice.
IsPowerOfTwo(number n)
Is n a number power of 2?
Parameter | Type | Default | Description |
---|---|---|---|
n | number | n |
- Return
- boolean:
true
if n equals 1, 2, 4, 8, 16...,nil
(for false) if not. - Error
- if n is not a number
flag_test(number set, number flag)
Test if a bit is set, the bit can be seen as a flag.
Parameter | Type | Default | Description |
---|---|---|---|
set | number | A sum of flags | |
flag | number | The big to test, a number power of 2. |
- Return
- boolean:
true
if flag is already set,nil
(for false) if not. - Error
- if set is not a number or if flag is not a power of 2.
- Example
Include "SMUtils" local face = FACE_ITALIC + FACE_BOLD local x = flag_test(face, FACE_UNDERLINE) --> x = nil (false) x = flag_test(face, FACE_BOLD) --> x = true
flag_set(number set, number flag)
Set a bit to 1, the bit can be seen as a flag.
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.NumberOfBars
or staff is notnil
and not a Staff.
SaveScoreAppearance(Score score, string setName, boolean full)
Save score appearance settings in a file.
Harmony Assistant only allow to save one default set, but you may need several sets, for solo parts, for conductor...
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
GetFilesInFolder(string folder, string mask, boolean recursive, boolean fullPath)
BrowseFolder(...)
needs a callback function, and has a bug: here is a fixed and simplified version.
Parameter | Type | Default | Description |
---|---|---|---|
folder | string | Folder name | |
mask | string | "*.*" | Mask to search file, e.g. "*.myr", "a*.*" |
recursive | boolean | false | true to browse sub-folders |
fullPath | boolean | false | true returns the full path, false returns only file names |
- Return
- table: File names: array of string, in alphabetic order
FileReadLines(string path, int stringEncoding, int crlf, boolean errorIfNotFound)
Syntaxic sugar to read all lines of a file, and return a table of them.
Note:
- encoding is supposed to be UTF-8 BOM and lines terminated by Macintosh CR.
- Convenient for small files when full content have to been read and stored.
Parameter | Type | Default | Description |
---|---|---|---|
path | string | The full path of the file to read. | |
stringEncoding | int | UTF8_STR_ENCODING | String encoding constant from MSDefine, e.g. UNKNOWN_STR_ENCODING |
crlf | int | MAC_CR | Carriage return constant from MSDefine, MAC_CR, LINUX_CR, WIN_CR, UNKNOWN_CR |
errorIfNotFound | boolean | (defaut=true) Throw error if file is not found, else return an empty table. |
- Return
- table: Table of string, one item per line
- Errors
- if argument is not a string
- if file can't be read
- See
- FileWriteLines
- Example
local lines = FileReadLines("/path/to/myConfigFile.txt") print(lines[1]) -- first line of the config file
FileWriteLines(string path, table lines, function formatFunc, int stringEncoding, int crlf)
Syntaxic sugar to writes a table of strings as lines in a file.
Collection and Map are also handled, and an optional formating function can transform lines before writing. Notes:
- The file is overwritten,
- Encoding is UTF-8 BOM and lines are terminated by Macintosh CR.
Parameter | Type | Default | Description |
---|---|---|---|
path | string | The full path of the file to write | |
lines | table | The lines to write, can be a table, a Collection or a Map | |
formatFunc | function | nil | Formatting function that receive two arguments and must return a string that will be written into the file. Arguments are:
nil then table and Collection prints their values, Map prints key and values separated by a space char. |
stringEncoding | int | UTF8_STR_ENCODING | String encoding constant from MSDefine, e.g. HTML_STR_ENCODING |
crlf | int | MAC_CR | Carriage return constant from MSDefine, MAC_CR, LINUX_CR, WIN_CR, UNKNOWN_CR |
- Errors
- if arguments have bad type.
- if file can't be written.
- See
- FileReadLines
- Examples
local lines = FileReadLines("/path/to/myConfigFile.txt") lines[1] = "0" -- change a value in the config file FileWriteLines("/path/to/myConfigFile.txt", lines)
local map = Map:new("number", "string", SORT_ASCENDING) map:put(1, "one"); map:put(2, "two"); map:put(3, "three") FileWriteLines("/path/to/file/count.txt", map, function(key,value) return tostring(key).."="..strupper(value); end) ) -- outputs 3 lines 1=ONE, 2=TWO and 3=THREE
CopyFreeObjects(Score src, Score dest)
Copy free objects from one Score to another.
FreeObject visible only on a specific view are copied to the view with the same name, else to all views.
All properties, including tags, are copied.
- 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
true
if recording,nil
(for false) if not - Example
if BatchIsRecording("Score") == true then BatchAdd("Score", "My action", MyFunction) else MyFunction(FrontScore()) end
BatchAdd(string batchName, string label, function func)
Stack a function for batch processing.
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.
ScriptReadVersion(string file)
Read the version of a script.
Look for the --VERSION: x.y in first 30 lines of source code.
Parameter | Type | Default | Description |
---|---|---|---|
file | string | Script file name (or full path) |
- Return
- string: A version in the x.y.z or yyyyMMdd form (as source code), or
nil
if file doesn't exist or version not found.
DeleteDisabledCurves(Staff staff)
Remove the parameter curves that have been disabled.
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
nil
if user canceled the choice.
TargetVisibility(Score score, Target target, boolean visible)
Turn one or all targets visible or hidden.
The property for visibility Target.DisplayCaption
is an inverted boolean. This function makes your code more comprehensible, and if inversion is fixed in a future version, you won't have to modify your code.
This doesn't regenerate captions nor refresh the score on screen.
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.
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 |
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
- Example
print(strfind("abcd", "b", 1, true)) --> 2 2 local pos = strfind("abcd", "b", 1, true) --> 2, one data lost local t = ElementsToTable(strfind("abcd", "b", 1, true)) --> {2, 2}
TableToElements(table t)
Bugfix version of MSLibrary's PushAllTableElts(t)
, return all elements of a table as multiple return values.
PushAllTableElts(...)
doesn't hnandle string nor complex objects, this version does.
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
- Example
local t = {1, "b", 3, FrontScore()} print(TableToElements(t)) --> 1 b 3 userdata(...) -- PushAllTableElts(t) returns 1 nil 3 and crashes
CopyBarNumberings(Staff source, Staff dest)
Copy bar numberings settings from one staff to another.
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)