lua-users home
lua-l archive

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


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:

function CommonPrefix(...)
  local iterator=function(...)
    local T={...}
    local n=#T
    return function()
      if n>=1 then
        n=n-1
        return T[n+1]
      else
        n=#T
      end
    end
  end

  local result={}
  local eos=false
  while not eos do
    local char, pos=nil, #result+1
    for x in iterator(...) do
      if not char then
        char=x:sub(pos,pos)
        if char=='' then return (table.concat(result)) end
      else
        if char~=x:sub(pos,pos) then
          eos=true
          return table.concat(result)
        end
      end
    end
    result[#result+1]=char
  end
  return table.concat(result)
end

Good luck,
miko