views:

1118

answers:

4

In many languages you can concatenate strings on variable assignment. I have a scenario, using the Lua programming language, where I need to append the output of a command to an existing variable. Is there a functional equivalent in Lua to the below examples?

Examples of other languages:

===== PERL =====
$filename = "checkbook";
$filename .= ".tmp";
================

===== C# =====
string filename = "checkbook";
filename += ".tmp";
===============

Thank you in advance for your help.

A: 

Strings can be joined together using the concatenation operator ".."

this is the same for variables I think

Jambobond
+3  A: 

Concatenation:

The string concatenation operator in Lua is denoted by two dots ('..'). If both operands are strings or numbers, then they are converted to strings according to the rules mentioned in §2.2.1. Otherwise, the "concat" metamethod is called (see §2.8).

from: http://www.lua.org/manual/5.1/manual.html#2.5.4

dcruz
+2  A: 

If you are asking whether there's shorthand version of operator .. - no there isn't. You cannot write a ..= b. You'll have to type it in full: filename = filename .. ".tmp"

sbk
+2  A: 

As other answers have said, the string concatenation operator in Lua is two dots.

Your simple example would be written like this:

filename = "checkbook"
filename = filename .. ".tmp"

However, there is a caveat to be aware of. Since strings in Lua are immutable, each concatenation creates a new string object and copies the data from the source strings to it. That makes successive concatenations to a single string have very poor performance.

The Lua idiom for this case is something like this:

function listvalues(s)
    local t = { }
    for k,v in pairs(s)
        t[#t+1] = tostring(v)
    end
    return table.concat(t,"\n")
end

By collecting the strings to be concatenated in an array t, the standard library routine table.concat can be used to concatenate them all up (along with a separator string between each pair) without unnecessary string copying.

RBerteig