Technology Apple

The Explode Function Translated to LUA / Corona SDK

Every development platform tends to have its own strengths and weaknesses, and one thing I've always tried to do is take the strength of one language with me when developing in a new language.  One function I found extremely useful in PHP was the explode function.   The explode function takes a delimited string and splits it into an array containing the individual pieces of data, so using the explode function against the string "1-2-3-4-5" will produce an array with those numbers.

 

The obvious use for this function is dealing with comma delimited files, but it can be useful in many other situations.  For example, those using my guidelines on how to save and retrieve settings information using a database table in LUA can utilize the explode function to save an array of values.   Simply create a delimited string of the values and save them to the database, and when you are ready for them, call the retrieve function and run the explode function.  Because calls to the database can run slower on mobile devices, this can be quicker than running multiple queries against the database for each individual piece of date.

Here's the explode function translated into LUA:

function explode(str,pattern)
    local values={};
    local pos=0;
    while (strpos(str,pattern)>0) do
        pos=string.find(str,pattern,0,true);
        if (pos==nil) then pos=0; end
        local val=string.sub(str,1,pos-1);
        str=string.sub(str,pos+1);
        table.insert(values,val);
    end
        
    if (string.len(str)>0) then 
        table.insert(values,str); 
    end
    
    return values;
end


This function can be called to break apart a delimited string. For example:

values=explode('a,b,c',',');

This call returns these values:

values[1]='a'
values[2]='b'
values[3]='c'


You can put the explode function in a helper file that is used in all of your projects along with any other function that you find yourself building and using over and over again.

How to Develop iPad Apps

Related posts "Technology : Apple"

Removal of an iPhone 3G Digitizer

Apple & Products

How to Unlock an iPhone 8Gb

Apple & Products

How to Connect the HTC Touch to WiFi

Apple & Products

How to Upload an M4P to an iPhone

Apple & Products

How to Get Into the iPod Control Folder

Apple & Products

How to Add or Remove iPod Music

Apple & Products

How to Convert iTouch Movies

Apple & Products

How to Download Apps to My New iPhone

Apple & Products

The Top Uses for an iPod Touch

Apple & Products

Leave a Comment