Skip to content

Template strings #98

@TwitchBronBron

Description

@TwitchBronBron

BrighterScript should support string literals like other languages.

C# has the verbatum identifier for capturing newlines and the interpolated string character $ for variable interpolation.

JavaScript has template literals which uses the backtick instead of quotes, and inlined variables are escaped with ${ and }. I prefer the javascript approach so that is what I am proposing.

It should:

Capture and stringify variables

BrighterScript

name = "John"
age = 42
isAlive = true
print `Hello ${name}, you are ${age} years old and isAlive=${isAlive}`

Transpiled

name = "John"
age = 42
isAlive = true
'split by line for readability, probably no newlines in actual transpile
print bs_templateString([
    "Hello ", 
    ", you are ", 
    " years old and isAlive="
], [
    name, 
    age,
    isAlive
])

prints "Hello John, you are 42 years old and isAlive=true"

Capture newlines

BrighterScript

multiLineMessage = `
    hello
    world
`

Transpiled

multiLineMessage = chr(10) + "    hello"  + chr(10) + "    world" + chr(10)

Transpiling

For template strings that have no variable interpolation and no newlines, we can simply transpile them to regular strings.
`hello world`
transpiles to
"hello world"

For captured newlines, we should turn the string into a string concatenation (see the Capture newlines section above)

For variable interpolation, we should follow the way javascript handles template literals by passing an array of strings, and an array of interpolated values. This allows us to avoid performance issues when checking the string values so we only need to inspect the variable values when determining how to stringify them.

the bslib_templateString function will need to identify the types of all variables in order to accurately know how to stringify them. So there will be a slight performance hit. However, developers always have the option to call their own stringify method on variables ahead of time if they already know what the variable type is.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions