Section Strings

strings utility functions

Summary

ConstantTypeSummary
UNICODE_DELTAstringUnicode delta: U+0394 = Δ
UNICODE_DOUBLE_FLATstringUnicode double flat: U+1D12B = 𝄫
UNICODE_DOUBLE_SHARPstringUnicode double sharp: U+1D12A = 𝄪
UNICODE_FLATstringUnicode flat: U+266D =
UNICODE_NATURALstringUnicode natural: U+266E =
UNICODE_SHARPstringUnicode sharp: U+266F =
UNICODE_SLASHED_OstringUnicode slashed-O: U+00F8 = ø
Return typeFunction and summary
stringCompareMyrScriptVersion(string version)
Is MyrScript =, < or > version x.y.z?
stringCompareVersions(string a, string b)
Compare two version numbers in x.y.z string format.
 Deserialize(string str)
Deserialize a string into object.
number, numberDrawText(Graph graphContext, string text, string fontFamily, int fontSize, int fontFace, number left, number top, number right, number bottom, int verticalAlign, int horizontalAlign, boolean allowOverflow, int originX, int originY, boolean autoLineBreak, Score score)
Draw a text, using given font family, size and face, aligned within boundaries.
stringEscapePercent(string str)
Escape a string that contain a % that can be interpreted in Lua string functions like gsub.
booleanIsNumeric(string str)
Is str representing a number?
booleanIsStyledString(string str)
Test if a string is a StyledString
 RemoveDiacritics(string s)
Remove diacritics (accents) from the string s.
string, intSMPitchToString(int pitch, int preferredAccidental, int compatible, string preferredNote)
Extension and bugfix for builtin PitchToString function.
int, intSMStringToPitch(string name)
Extension and bugfix for builtin StringToPitch function.
stringSerialize(obj)
Serialize an object to store it as string and later deserialization.
string, stringSplitPath(string path)
Split a path into directory and file, no file if path ends by a '/'.
tableSplitUrl(string url)
Split an URL into protocol, host, path, query and anchor.
number, numberStringSizes(Graph graphContext, string s, string fontFamily, int fontSize, int fontFace, Score score)
Get the string size using given font family, size and face.
stringescape_lines(string s)
Escape lines \n and \r as well as tabs \t and backslash \, using backslashes \.
stringexcel_column_name(int n)
Returns the Excel column name of the n-th column.
stringgsub_args(string str, ...)
Replace %1, %2 in str by first and second following arguments.
stringstring_between(string str, string left, string right)
Return the portion of str found between left and right.
stringstring_concat(string src, string delimiter, ...)
Concatenate toAdd after src with a delimiter, handles nil and empty string initialization.
booleanstring_ends_with(string str, string rightStr)
Does str ends with rightStr?
stringstring_first(string a, string b)
Returns the first of a and b in alphabetical order.
stringstring_join(table list, string delimiter)
Concat the elements of table list, separated by the string delimiter.
stringstring_last(string a, string b)
Returns the last of a and b in alphabetical order.
stringstring_left(string str, int n)
Return the n leftmost chars of the string str.
stringstring_line_to_space(string str)
Replace line \r and \n characters by a space.
stringstring_right(string str, int n)
Return the n rightmost chars of the string str.
tablestring_slice(string s, int sze, boolean fromEnd)
Slice the string into blocks of size, except last one that may be shorter.
tablestring_split(string s, string delim, int limit)
Split the string s by a string delimiter delim.
tablestring_split_lines(string s)
Split the string s by lines, handle \r, \n and \r\n.
booleanstring_starts_with(string str, string leftStr)
Does str starts with leftStr?
stringstring_time(number seconds, boolean exact, boolean clockFormat)
Converts a time (music duration, debug chrono...) into readable string.
stringstring_trim(string s, string toTrim, string side)
Removes toTrim at the beginning and the end of s.
stringunescape_lines(string s)
Unescape lines \n and \r as well as tabs \t and backslash \, escaped by backslashes.

Constants

string UNICODE_FLAT

Unicode flat: U+266D =

See
https://www.compart.com/fr/unicode/U+266D

string UNICODE_NATURAL

Unicode natural: U+266E =

See
https://www.compart.com/fr/unicode/U+266E

string UNICODE_SHARP

Unicode sharp: U+266F =

See
https://www.compart.com/fr/unicode/U+266F

string UNICODE_DOUBLE_FLAT

Unicode double flat: U+1D12B = 𝄫

See
https://www.compart.com/en/unicode/U+1D12B

string UNICODE_DOUBLE_SHARP

Unicode double sharp: U+1D12A = 𝄪

See
https://www.compart.com/en/unicode/U+1D12A

string UNICODE_DELTA

Unicode delta: U+0394 = Δ

See
https://www.compart.com/fr/unicode/U+0394

string UNICODE_SLASHED_O

Unicode slashed-O: U+00F8 = ø

See
https://www.compart.com/fr/unicode/U+00F8

Functions

CompareMyrScriptVersion(string version)

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

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

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

CompareVersions(string a, string b)

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

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

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

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

Extension and bugfix for builtin PitchToString function.

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

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

SMStringToPitch(string name)

Extension and bugfix for builtin StringToPitch function.

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

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

Serialize(obj)

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

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

Deserialize(string str)

Deserialize a string into object.

ParameterTypeDefaultDescription
strstring str
Return
Copy of previously serialized object

StringSizes(Graph graphContext, string s, string fontFamily, int fontSize, int fontFace, Score score)

Get the string size using given font family, size and face.

Multi-line is not handled.

ParameterTypeDefaultDescription
graphContextGraph The GraphContext: dialog.GraphContext, surface.GraphContext...
sstring The string, rich string is handled, tokens are transformed (e.g. Moderato $(4) = 80)
fontFamilystring"geneva" 
fontSizeint11 
fontFaceintFACE_NONESum of FACE_* constants in MSDefine
scoreScorenilA Score need for special command replacements such as "$T" replaced by score's title.
Returns
number: Width of the string.
number: Height of the string.

DrawText(Graph graphContext, string text, string fontFamily, int fontSize, int fontFace, number left, number top, number right, number bottom, int verticalAlign, int horizontalAlign, boolean allowOverflow, int originX, int originY, boolean autoLineBreak, Score score)

Draw a text, using given font family, size and face, aligned within boundaries.

This may be useful if you create your own component that need to display text.

ParameterTypeDefaultDescription
graphContextGraph The GraphContext: dialog.GraphContext, surface.GraphContext...
textstring The text to draw, rich strings are handled, tokens are transformed (e.g. $(4) = 80)
fontFamilystring"geneva" 
fontSizeint11 
fontFaceintFACE_NONESum of FACE_* constants in MSDefine
leftnumber Left boundary
topnumber Top boundary
rightnumber Right boundary
bottomnumber Bottom boundary
verticalAlignint VERTICAL_ALIGN_TOP, VERTICAL_ALIGN_MIDDLE or VERTICAL_ALIGN_BOTTOM
horizontalAlignint ALIGN_LEFT, ALIGN_CENTER or ALIGN_RIGHT
allowOverflowbooleantrueAccepts that text can be displayed outside of the boundaries? If not allowed, alignment may be changed to minimize the risk of truncation.
originXintnilHorizontal origin of alignment, e.g. right aligned from the center (left+bottom)/2
originYintnilVertical origin of alignment, e.g. top aligned from 1/3 of the height.
autoLineBreakbooleanfalseSplit text into lines to try to avoid horizontal overflow?
scoreScorenilIn case of text with tokens like $T (title), $N (number of pages), if score is provided, tokens are transformed. See Text commands in manual.
Returns
number: Width needed to draw the full text, even if it overflows and as been truncated.
number: Height needed to draw the full text, even if it overflows and as been truncated.

IsStyledString(string str)

Test if a string is a StyledString

ParameterTypeDefaultDescription
strstring str
Return
boolean: true or nil (for false).

IsNumeric(string str)

Is str representing a number?

ParameterTypeDefaultDescription
strstring The string to test
Return
boolean: true or nil (for false)
Example

IsNumeric("-22.5") --> true
 IsNumeric("-.5") --> true
 IsNumeric(".12") --> true
 IsNumeric("0.12") --> true
 IsNumeric("1.") --> false
 IsNumeric("123abc") --> false

EscapePercent(string str)

Escape a string that contain a % that can be interpreted in Lua string functions like gsub.

ParameterTypeDefaultDescription
strstring str
Return
string: % are escaped by a %.

string_split(string s, string delim, int limit)

Split the string s by a string delimiter delim.

ParameterTypeDefaultDescription
sstring The string to split
delimstring The delimiter
limitint0Maximum number of slices of string, values <= 1 are ignored..
Return
table: An array of at least one item (s if delim is not found)
Example

local t = string_split("Hello World!", " ")
 print(t[1]) --> Hello
 print(t[2]) --> World!

string_split(string s, string delim, int limit)

Split the string s by a string delimiter delim.

ParameterTypeDefaultDescription
sstring The string to split
delimstring The delimiter
limitint0Maximum number of slices of string, values <= 1 are ignored..
Return
table: An array of at least one item (s if delim is not found)
Example

local t = string_split("Hello World!", " ")
 print(t[1]) --> Hello
 print(t[2]) --> World!

string_split_lines(string s)

Split the string s by lines, handle \r, \n and \r\n.

ParameterTypeDefaultDescription
sstring The string to split
Return
table: A table of at least one element (s if line separator is not found)

string_split_lines(string s)

Split the string s by lines, handle \r, \n and \r\n.

ParameterTypeDefaultDescription
sstring The string to split
Return
table: A table of at least one element (s if line separator is not found)

string_slice(string s, int sze, boolean fromEnd)

Slice the string into blocks of size, except last one that may be shorter.

ParameterTypeDefaultDescription
sstring The string to slice
szeint Size of each slice
fromEndboolean (defaul=false) Slice from the end of the string, it means that, when there are multiple slices, if fromEnd == true, first slice's length may be smaller than size, if fromEnd == false last slice's length may be smaller than size.
Return
table: A table of slices of s
Error
if s is not a string, or size is not a positive number

string_join(table list, string delimiter)

Concat the elements of table list, separated by the string delimiter.

ParameterTypeDefaultDescription
listtable list
delimiterstring delimiter
Return
string: string
Example

string_join({"Anna", "Bob", "Charlie", "Dolores"}, ", ")
 --> Anna, Bob, Charlie, Dolores

string_join(table list, string delimiter)

Concat the elements of table list, separated by the string delimiter.

ParameterTypeDefaultDescription
listtable list
delimiterstring delimiter
Return
string: string
Example

string_join({"Anna", "Bob", "Charlie", "Dolores"}, ", ")
 --> Anna, Bob, Charlie, Dolores

string_concat(string src, string delimiter, ...)

Concatenate toAdd after src with a delimiter, handles nil and empty string initialization.

  • s is not concatenated if empty,
  • delimiter is not inserted if src is nil or empty.
myList = string_concat(myList, ", ", "an item") is a a shortcut for myList = (myList and (myList..", ") or "") .. "an item" with more nil handling.

ParameterTypeDefaultDescription
srcstring src
delimiterstring"" 
...  List of string or number.
Return
string: string
Error
if s is nil

string_trim(string s, string toTrim, string side)

Removes toTrim at the beginning and the end of s.

ParameterTypeDefaultDescription
sstring If nil, returns ""
toTrimstring" \t\r\n"List of chars to remove, if nil, then trim spaces, tabs, lines.
sidestring"both"Side of the trim, "left", "right" or anything else for both sides.
Return
string: The trimmed string
Example

string_trim(" abcd\t")) --> "abcd"
 string_trim(" abcd\t", nil, "left") --> "abcd\t"
 string_trim(" abcd\t", "a \t") --> "bcd"
 string_trim(" abcd\t", "()") --> " abcd\t"

string_left(string str, int n)

Return the n leftmost chars of the string str.

ParameterTypeDefaultDescription
strstring str
nint n
Return
string: A string of strlen(str) to n chars: strsub(str, 1, n)
Error
if str is not a string or n <= 0

string_right(string str, int n)

Return the n rightmost chars of the string str.

ParameterTypeDefaultDescription
strstring str
nint n
Return
string: A string of strlen(str) to n chars: strsub(str, -n)
Error
if str is not a string or n <= 0

string_starts_with(string str, string leftStr)

Does str starts with leftStr?

ParameterTypeDefaultDescription
strstring str
leftStrstring leftStr
Return
boolean: true if string_left(str, strlen(leftStr)) == leftStr, nil for false.
Error
if str is not a string, or strlen(leftStr) == 0

string_ends_with(string str, string rightStr)

Does str ends with rightStr?

ParameterTypeDefaultDescription
strstring str
rightStrstring rightStr
Return
boolean: true if string_right(str, strlen(rightStr)) == rightStr, nil for false.
Error
if str is not a string, or strlen(rightStr) == 0

string_between(string str, string left, string right)

Return the portion of str found between left and right.

ParameterTypeDefaultDescription
strstring str
leftstring left
rightstring right
Return
string: nil if left or right are not found in str.

string_line_to_space(string str)

Replace line \r and \n characters by a space.

ParameterTypeDefaultDescription
strstring str
Return
string: string

excel_column_name(int n)

Returns the Excel column name of the n-th column.

"A" for 1, "B" for 2, "Z" for 26, "AA" for 27...

ParameterTypeDefaultDescription
nint n
Return
string: string
Example

excel_column_name(123) --> "DS"

string_time(number seconds, boolean exact, boolean clockFormat)

Converts a time (music duration, debug chrono...) into readable string.

ParameterTypeDefaultDescription
secondsnumber Time in seconds, 0.010 = 10ms
exactbooleanfalseIf false, removes details (e.g. no milliseconds if time is minutes and you don't need so much precision).
clockFormatbooleanfalseClock format: returns 00:03.010 instead of 3s 10ms
Return
string: "10 ms", "3 s 456 ms", "1 min 14 s", 00:03.010...
See
Stopwatch:new
Example


 s = 1.0102345 -- 1 second, 10,2345 ms
 print(string_time(s)) --> "1.01 s"
 print(string_time(s, true)) --> "1 s 10.234 ms"
 print(string_time(s, false, true)) --> "00:01.010"
 print(string_time(s, true, true)) --> "00:01.010234"
 s = s + 2*60 -- add 2 minutes
 print(string_time(s)) --> "2 min 1 s"
 print(string_time(s, true)) --> "2 min 1 s 10.234 ms"
 print(string_time(s, false, true)) --> "02:01.010"
 print(string_time(s, true, true)) --> "02:01.010234"

string_time(number seconds, boolean exact, boolean clockFormat)

Converts a time (music duration, debug chrono...) into readable string.

ParameterTypeDefaultDescription
secondsnumber Time in seconds, 0.010 = 10ms
exactbooleanfalseIf false, removes details (e.g. no milliseconds if time is minutes and you don't need so much precision).
clockFormatbooleanfalseClock format: returns 00:03.010 instead of 3s 10ms
Return
string: "10 ms", "3 s 456 ms", "1 min 14 s", 00:03.010...
See
Stopwatch:new
Example


 s = 1.0102345 -- 1 second, 10,2345 ms
 print(string_time(s)) --> "1.01 s"
 print(string_time(s, true)) --> "1 s 10.234 ms"
 print(string_time(s, false, true)) --> "00:01.010"
 print(string_time(s, true, true)) --> "00:01.010234"
 s = s + 2*60 -- add 2 minutes
 print(string_time(s)) --> "2 min 1 s"
 print(string_time(s, true)) --> "2 min 1 s 10.234 ms"
 print(string_time(s, false, true)) --> "02:01.010"
 print(string_time(s, true, true)) --> "02:01.010234"

string_first(string a, string b)

Returns the first of a and b in alphabetical order.

Comparable to max(a,b) for numbers.

ParameterTypeDefaultDescription
astring a
bstring b
Return
string: string
Example

print(string_first("Hello", "Harmony")) --> "Harmony"

string_last(string a, string b)

Returns the last of a and b in alphabetical order.

Comparable to max(a,b) for numbers.

ParameterTypeDefaultDescription
astring a
bstring b
Return
string: string
Example

print(string_last("Harmony", "Assistant")) --> "Harmony"

SplitUrl(string url)

Split an URL into protocol, host, path, query and anchor.

ParameterTypeDefaultDescription
urlstring url
Return
table: Table t with following structure for https://www.myriad-online.com/cgi-bin/bbs/YaBB.pl?board=MYRSCRIPT;action=display;num=1652718688#2
t.Protocol = "https"
 t.Host = "www.myriad-online.com"
 t.Path = "cgi-bin/bbs/YaBB.pl"
 t.Query = "board=MYRSCRIPT;action=display;num=1652718688"
 t.Anchor = "2"
Some of these field may be empty string or nil
Error
if url is nil or empty string

SplitPath(string path)

Split a path into directory and file, no file if path ends by a '/'.

ParameterTypeDefaultDescription
pathstring path
Returns
string: directory
string: file name

RemoveDiacritics(string s)

Remove diacritics (accents) from the string s.

ParameterTypeDefaultDescription
sstring s
Return
The string without diacritics, e.g. 'รก' is replaced by 'a'.
Error
if s is not a string
See
https://en.wikipedia.org/wiki/Diacritic

escape_lines(string s)

Escape lines \n and \r as well as tabs \t and backslash \, using backslashes \.

ParameterTypeDefaultDescription
sstring A string that may contain CR and/or LF
Return
string: escaped string.
See
unescape_lines
Example


 s = "string\twith\nnew line"
 print(s) --> string  with
          --> new line
 print(escape_lines(s)) --> string\twith\nnew line

unescape_lines(string s)

Unescape lines \n and \r as well as tabs \t and backslash \, escaped by backslashes.

ParameterTypeDefaultDescription
sstring A escaped string
Return
string: unescaped string ready to be printed.
See
escape_lines
Example


 s = "string\\twith\\nnew line"
 print(s) --> string\twith\nnew line
 print(unescape_lines(s)) --> string  with
                          --> new line

gsub_args(string str, ...)

Replace %1, %2 in str by first and second following arguments.

This is a convenient way to write the following code:
return gsub(gsub(str, "%%1", "1st value"), "%%2", "2nd value")

gsub return 2 value, the string and number of substitutions. Strangely, nested gsub accept the second returned value, but if you write gsub(str, 1, "%%2", "2nd value") you get an error.
But the second returned value may disturb your functions!
This variant return only the modified string, it may save you debugging headaches ;)

ParameterTypeDefaultDescription
strstring The string containing %1, %2... to be replaced
...  Undefined number of arguments that must be string, number or nil.
Return
string: The replaced string
Error
If one argument has unsupported type.
Example


 local s = "Hello %1, I want %2."
 print(gsub_args(s, "Bob", "bananas")) --> Hello Bob, I want bananas.