Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the neatest way to split out a Path Name into its components in Lua

Tags:

I have a standard Windows Filename with Path. I need to split out the filename, extension and path from the string.

I am currently simply reading the string backwards from the end looking for . to cut off the extension, and the first \ to get the path.

I am sure I should be able to do this using a Lua pattern, but I keep failing when it comes to working from the right of the string.

eg. c:\temp\test\myfile.txt should return

  • c:\temp\test\
  • myfile.txt
  • txt

Thank you in advance apologies if this is a duplicate, but I could find lots of examples for other languages, but not for Lua.

like image 876
Jane T Avatar asked Mar 09 '11 08:03

Jane T


People also ask

How do I cut a string in Lua?

A very simple example of a split function in Lua is to make use of the gmatch() function and then pass a pattern which we want to separate the string upon.

How do I use GSUB Lua?

gsub() function has three arguments, the first is the subject string, in which we are trying to replace a substring to another substring, the second argument is the pattern that we want to replace in the given string, and the third argument is the string from which we want to replace the pattern.

What is Lua_path?

Lua modules and packages - what you need to know As with most search paths, the LUA_PATH is actually a semicolon-separated collection of filesystem paths. Lua scans them in the order they are listed to find a module. If the module exists in multiple paths, the module found first wins and Lua stops searching.


1 Answers

Here is an improved version that works for Windows and Unix paths and also handles files without dots (or files with multiple dots):

= string.match([[/mnt/tmp/myfile.txt]], "(.-)([^\\/]-%.?([^%.\\/]*))$") "/mnt/tmp/" "myfile.txt"    "txt"  = string.match([[/mnt/tmp/myfile.txt.1]], "(.-)([^\\/]-%.?([^%.\\/]*))$") "/mnt/tmp/" "myfile.txt.1"  "1"  = string.match([[c:\temp\test\myfile.txt]], "(.-)([^\\/]-%.?([^%.\\/]*))$") "c:\\temp\\test\\"  "myfile.txt"    "txt"  = string.match([[/test.i/directory.here/filename]], "(.-)([^\\/]-%.?([^%.\\/]*))$") "/test.i/directory.here/"   "filename"  "filename" 
like image 145
Paul Kulchenko Avatar answered Sep 24 '22 23:09

Paul Kulchenko