Add template strings

Right now to inject a bunch of dynamic text into a literal string you have to do one of two things:

a = 'is'
b = 'example'
c = 'code'

option1 = ('this %s an %s of %s'):format(a, b, c)
option2 = 'this ' .. a .. ' an ' .. b .. ' of ' .. c

With template strings you can do this in a way that’s much easier to process visually:

option3 = `this {a} an {b} of {c}`

Everything within braces gets interpreted by lua and automatically concatenated to the string.

See javascript implementation: Template literals (Template strings) - JavaScript | MDN (mozilla.org)

11 Likes

I would’ve preferred the syntax used in Swift for this option3 := "this \(a) an \(b) of \(c)". I don’t believe it breaks major compatibility as \( isn’t used to escape anything for a string literal and it enhances the existing string literal. (This includes 'this \(a) an \(b) of \(c)' but not [=[thiis \(a) an \(b) of \(c)]=])

C# and Visual Basic syntax for this could work too option3 := $"this {a} an {b} of {c}".

2 Likes

$"" is a good idea. Can extend this to $'', $[[]], $[=[]=], etc too.

I’m not a fan of anything that requires more than two symbols for enclosure. In order to not break existing games this will require a new syntax for string literals. It doesn’t need to use escapes like \(a) or ${a}.

3 Likes

Template strings for long strings don’t make sense, they are made for literal text and don’t interpret special sequences except for the ending sequence.

Using a $ for string literals is confusing, since they may be used for a function call without parentheses. a$"b" looks like a weird $ operator more than a part of the string literal.

What should happen if a, b, or c are not a string?

Every input gets tostringed.

No? Template strings process escape sequences as usual, in javascript at least. Even if they didn’t I don’t see how that would preclude it from being a useful feature. The only way to write escapeless literal strings in lua is to use bracket strings, which is compatible with the $ notation discussed earlier.