Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
string manipulation — Gideros Forum

string manipulation

piepie Member
edited March 2015 in General questions
I am playing a bit with lfs, and I was wondering how to "split" a path into directories.

I found a lot of examples and snippets on how to retrieve a base directory , filenames and extensions from a given path, but I didn't find anything to "split" a path (string) as I like.
"/sdcard/dir1/banana/"   --->    "/sdcard/dir1/"     "banana/"   or --->  "/sdcard/"     "dir1/"     "banana/"
 "C:/dir1/banana/" ----> "C:/dir1/"            "banana/"    or  ---->   "C:"    "/dir1/"          "banana/"


I found about the lua string pattern, I thought I would be using string.match, but after some hours wasted on that, I think that writing patterns is something currently out of my league.. ~X(
I could really use some hint :)

My goal was being able to follow the directory path backwards: starting from banana to root.

Thank you

Comments

  • OZAppsOZApps Guru
    edited March 2015 Accepted Answer
    Hi Pie,
    If you have a copy of my Book, on Page 74, there is a function that exists to split strings. It is simply 4 lines of code and are
     function string:split(sep)
      local sep, fields = sep or ":", {}
      local pattern = string.format("([^%s]+)", sep)
      self:gsub(pattern, function(c) fields[#fields + 1] = c end)
      return fields
     end
    and to use it, try something like
    str = ":sdcard:dir1:banana:" 
    results = str:split(":")
    -- You have the split data in the table.
    Get the number of elements in the table via #results. Hope that helps resolve your issue.

    cheers,

    Jayant C Varma

    Author of :
    * Learn Lua for iOS Game Development, Apress
    * Xcode 6 Essentials, Packt
    * More iPhone Development with Swift, Apress
    * More iPhone Development with Objective-C, Apress
    twitter: @ozapps | http://www.oz-apps.com | http://howto.oz-apps.com | http://reviewme.oz-apps.com
    Author of Learn Lua for iOS Game Development from Apress ( http://www.apress.com/9781430246626 )
    Cool Vizify Profile at https://www.vizify.com/oz-apps
    +1 -1 (+5 / -0 )Share on Facebook
  • piepie Member
    edited March 2015
    Thank you @OzApps, I found a typo in the split function:

    local pattern = string.format("([^%s]+)", sep) was missing a " )"
    function string:split(sep)
      local sep, fields = sep or ":", {}
      local pattern = string.format("([^%s]+)", sep) 
      self:gsub(pattern, function(c) fields[#fields + 1] = c end)
      return fields
     end
    Now it seems to work :) thank you very much!
Sign In or Register to comment.