tags:

views:

43

answers:

1

I know that I can concatenate strings in Lua like so

String = String .. 'more'

But what if I want to add HTML and want to keep (obviously) the way it looks? For example, how do I overcome the

luac: Perl to Lua:226: unfinished string near '''

error I get when I do this

Html_string = Html_string .. "
                <tr>                                                                                         
                    <th class=row>" . gettext("Last Upgrade") . "</th>                                   
                    <td title=\"Upgrade_date\"Upgrade_status</td>                                     
                </tr>
                             "
+5  A: 

You can use multi-line string tokens.

In Lua, thats done using the [[ .. ]] syntax

So, for example:

  Html_string = Html_string .. [[
                <tr>                                                                                         
                    <th class="row">]] .. gettext("Last Upgrade") .. [[</th>                                   
                    <td title="Upgrade_date">Upgrade_status</td>                                     
                </tr>
  ]]

Inside of [[..]] you don't even have to escape any characters. If your html content happens to contain [[ ..]] itself, you can expand it to [=[ .. ]=] to avoid conflicts. This expansion can be done to any number of = signs, as long as its the same amount in the opening and closing tag.

See the PiL for reference, it even uses HTML as an example for the multiline strings.

http://www.lua.org/pil/2.4.html

Hendrik
Oh, God. Thank you so much for the answer, I can't believe how stupid I am. I knew I could do that with comments, I just didn't think it'd work with strings too.
OddCore
Thats what i love about Lua, everything boils down to a few key concepts. A multi-line comment is basically just a commented-out multi-line String. No special magic. :)
Hendrik
Would using `string.format` be more efficient than a bunch of concatenation operations?
Judge Maygarden
Efficient, well. depends. If you use the concats in one big block, its internally converted into one concat, and doesn't create much overhead. If you use alot of concats in seperate statements, it creates string garbage.However, i personally always prefer string.format. But in the case of very long text passages (like big block of HTML code), it might be easy to miss the replacement token in the middle, etc.
Hendrik