Page 1 of 1

Get path of filename

Posted: Tue Apr 22, 2014 9:03 pm
by Ivo
I want to write a function to get the path of a filename in a LÖVE program, and am finding it difficult. getDir('/usr/local/bin/sl') should return '/usr/local/bin'. I essentially want to remove the last item in a filename. In python I would just do:

Code: Select all

def getDir(sPath):
  dir = '/'.join(sPath.split('/')[:-1])
  return dir
but as far as I know lua does not have the split or the join functions.

Re: Get path of filename

Posted: Tue Apr 22, 2014 9:13 pm
by slime
Something like this:

Code: Select all

function getDir(filepath)
    return filepath:match("(.+)/") or ""
end
It will return a string containing everything up to the last '/' in the filepath, or an empty string if there isn't any '/'.

Re: Get path of filename

Posted: Tue Apr 22, 2014 9:28 pm
by Ivo
worked perfectly, thanks!