Murga-Projects Forums
concatenate nil - Printable Version

+- Murga-Projects Forums (http://www.murga-projects.com/forum)
+-- Forum: Project Forums (/forumdisplay.php?fid=1)
+--- Forum: MurgaLua - General (/forumdisplay.php?fid=2)
+--- Thread: concatenate nil (/showthread.php?tid=327)


concatenate nil - asafp - 07-07-2008 11:01 PM

Most of you know that lua throws a conniption when you try to concatenate a nil value. Often, it's not a big deal to check for a nil value first. But I've got bitten in the rear end more than once with a script that will run for a long time and then puke and die over this.

Is there a fairly seamless way to just do nothing when concatenating a nil value like most other languages do?


RE: concatenate nil - asafp - 07-08-2008 10:43 AM

I looked at metatables and couldn't get them to do anything right. I did read a lot about how great and wonderful and powerful and cool metatables are. I must be a moron as I couldn't get a single example I found to work and even if they did work, it sure seems that you could accomplish the same thing in a much more straightforward manner. But, I digress.

Anyway, I put together a couple of string concatenation functions that do what I need.

Code:
-- string concatenation functions that don't puke on nils
-- string.concat accepts a variable number of arguments and sticks them altogether ignoring any nils
-- string.concats accepts the first variable as a seperator and the remaining variables are stuck together with sep in between
-- if the first string.concats variable is nil, it works just like string.concat
string.concat = function(...)
local cur=nil
local prv=nil
for i=1,select('#',...) do
    cur=select(i,...)
    if prv==nil then
        prv=cur
    else
        if cur~=nil then
            prv=prv..cur
        end
    end
end
return prv
end
string.concats = function(...)
local cur=nil
local prv=nil
local sep=select(1,...)
if sep==nil then
    for i=1,select('#',...) do
        cur=select(i,...)
        if prv==nil then
            prv=cur
        else
            if cur~=nil then
                prv=prv..cur
            end
        end
    end    
else
    for i=2,select('#',...) do
        cur=select(i,...)
        if i==2 then
            prv=cur
        else
            if cur~=nil then
                prv=prv..sep..cur
            else
                prv=prv..sep
            end
        end
    end
end
return prv
end
x=string.concats(',','a','b',nil,'d')
print (x)
x=string.concats(nil,'a','b',nil,'d')
print (x)
x=string.concat(nil,'a','b',nil,'d')
print (x)
x=string.concats()
print (x)