lua-users home
lua-l archive

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


On 10.03.2011 09:37, Benoit Germain wrote:
> Hello,
> 
>  
> 
>  Let’s say I grabbed some string from a log window in an application of
> mine. I want to display a popup menu offering some actions if this
> string contains a file name. Even better, since I got this string
> because the user clicked it, I want to offer the actions if the clicked
> **word** inside that string represents an existing file.
> 
>  
> 
> So, I want to extract the word in this string whose limits surround the
> position clicked by the user. Is there some efficient way of searching
> for the beginning and end of a word around a given position that doesn’t
> involve reversing the string or capturing all words until I find one
> whose limits enclose the initial position?

I would find the choosen character, and then look for the closest
separator (delimiter) both after and before that character. For example:

s="A string with a file /tmp/file.txt inside the message"

function findStringAtPos(s, pos, sep)
  sep=sep or ' '
  local BUF={}
  local char=s:sub(pos, pos)
  local tmppos=pos
  while char~=sep or not char do
    BUF[#BUF+1]=char
    tmppos=tmppos+1
    char=s:sub(tmppos, tmppos)
  end
  tmppos=pos-1
  char=s:sub(tmppos, tmppos)
  while char~=sep or not char do
    table.insert(BUF, 1, char)
    tmppos=tmppos-1
    char=s:sub(tmppos, tmppos)
  end
  return (table.concat(BUF))
end

print(findStringAtPos(s, 5))
print(findStringAtPos(s, 25))

> What I am currently doing is even more brutal than that: I know that I
> look for a file path. So I iterate over all words, and check for each of
> them if the file exists. If true, I found a file and I can act on it J.
> But there is surely a better way…

OMG, for each string you make a system call :( Your hard drive does not
like this for sure.

Regards,
miko