News : The level of daily SPAM has reached insane proportions, all registrations are now manual. I ask you to send me an e-mail (john (at) murga (dot) org), to confirm that you want me to create an account for you.


Post Reply  Post Thread 
concatenate nil
Author Message
asafp
Member
***


Posts: 81
Group: Registered
Joined: Jan 2008
Status: Offline
Reputation: 0
Post: #1
RE: concatenate nil

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)

07-08-2008 10:43 AM
Visit this user's website Find all posts by this user Quote this message in a reply
Post Reply  Post Thread 

Messages In This Thread
concatenate nil - asafp - 07-07-2008, 11:01 PM
RE: concatenate nil - asafp - 07-08-2008 10:43 AM

View a Printable Version
Send this Thread to a Friend
Subscribe to this Thread | Add Thread to Favorites

Forum Jump: