Search code examples
lua

How to read a specific line only if contains a specific data


Basically im trying to get the last modified timestamp of a file without external libraries

OS: Windows

Code:

local cache_out = io.popen("dir /T:W %CD%\\data\\actions\\scripts\\cache.lua", "r")
local cache_data = cache_out:read("*a")

It prints:

enter image description here

My question is: How can start reading from 29/06/2021 to get the modified time which in this case is '04:45'? I know it can be done using string.find or string.gmatch but i have no clue how


Solution

  • Lua uses regex with its own classes for matching characters:

    .  -- all characters
    %a -- letters
    %c -- control characters
    %d -- digits
    %l -- lower case letters
    %p -- punctuation characters
    %s -- space characters
    %u -- upper case letters
    %w -- alphanumeric characters
    %x -- hexadecimal digits
    %z -- the character with representation 0.
    

    To get the class of all characters except the group just use uppercase. For example, if you want to match any character except space (like tab and space) you would use %S.

    To match multiple parts of a string you can use parenthesis in string.match() like so

    local d, t, _ = string.match(cache_data, "(%d%d/%d%d/%d+)%s+(%d%d:%d%d)%s+([ap].m.)")
    

    and just validate the data for anything other than nil.

    For more detailed info I recommend reading this https://www.lua.org/pil/20.2.html