6

Is there a way to use a heredoc type of notation in Lua that references variables within the string?

The basic idea of what I'm trying to do would look something like follows. The heredoc piece is fine, but within Lua you can't actually reference the variable in the manner I'm showing below.

username = "bigtunacan"    

sql=[=[
  SELECT * FROM users WHERE username='$bigtunacan';
]=]
bigtunacan
  • 4,873
  • 8
  • 40
  • 73
  • @NicolBolas it is a section of a source code file that is treated as if it were a separate file that had been loaded in place. https://en.wikipedia.org/wiki/Here_document They are often used for multi-line string literals as they are typically clearer than using regular string concatenation for long multi-line strings. In my sample I have a short string, but that was to simplify for purposes of my question. – bigtunacan Mar 28 '16 at 03:02
  • OK, so I should just pretend you said "multiline string literal" then? – Nicol Bolas Mar 28 '16 at 03:09
  • Yes; that's the simplest way to look at it. – bigtunacan Mar 28 '16 at 03:13

2 Answers2

7

There's no built-in string interpolation, but it can be trivially implemented with gsub and replacement table.

sql=[=[
  SELECT * FROM users WHERE username='$username';
]=]

print((sql:gsub('$(%w+)', { username = 'bigtucan' })))
-- SELECT * FROM users WHERE username='bigtucan';

Note an extra set of () - this is so only first return - the interpolated string is used from gsub and the 2nd - number of replacements made - silently discarded. This might be important if you use result of gsub as last in list of arguments to some function where adding one more argument might produce different behavior.

Also if you want to use this in SQL context, you really should use placeholders instead.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
0

There is no Lua construct that allows variable interpolation within any string. See Literal Strings in the official reference guide.

You could of course write a function that would parse it and do the substitutions.

Adam B
  • 3,775
  • 3
  • 32
  • 42