lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Michal Kolodziejczyk wrote:
> Petite Abeille wrote:
>> Hello,
>>
>> Does anyone has a little function to compute the common prefix of a list
>> of strings?
>>
>> E.g.:
>>
>> local aList = { 'foobarbaz', 'foobar', 'foo' }
>>
>> print( CommonPrefix( aList ) )
>>
>>> foo
> 
> Here is my try:

...and yet another - you may like this one:

function CommonPrefix(...)
  local anIterator=function(...)
    local TStrings={...}
    local numStrings=#TStrings
    local aCharPointer=1
    local aChar
    return function()
      aChar=TStrings[1]:sub(aCharPointer,aCharPointer)
      for i=2,numStrings do
        if aChar~=TStrings[i]:sub(aCharPointer,aCharPointer) then
          return nil
        end
      end
      aCharPointer=aCharPointer+1
      return aChar
    end
  end

  local aResult={}
  for aChar in anIterator(...) do
    aResult[#aResult+1]=aChar
  end
  return table.concat(aResult)
end

Regards,
miko