Search code examples
luastring-interpolation

Lua heredoc with variable interpolation?


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';
]=]

Solution

  • 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.