Search code examples
stringlua

How to parse a configuration file (kind of a CSV format) using LUA


I am using LUA on a small ESP8266 chip, trying to parse a text string that looks like the one below. I am very new at LUA, and tried many similar scripts found at this forum.

data="
-- String to be parsed\r\n
Tiempo1,20\r\n
Tiempo2a,900\r\n
Hora2b,27\r\n
Tiempo2b,20\r\n
Hora2c,29\r\n
Tiempo2c,18\r\n"

My goal would be to parse the string, and return all the configuration pairs (name/value). If needed, I can modify the syntax of the config file because it is created by me. I have been trying something like this:

var1,var2 = data:match("([Tiempo2a,]), ([^,]+)")

But it is returning nil,nil. I think I am on the very wrong way to do this.

Thank you very much for any help.


Solution

  • You need to use gmatch and parse the values excluding non-printable characters (\r\n) at the end of the line or use %d+

    local data=[[
    -- String to be parsed
    Tiempo1,20
    Tiempo2a,900
    Hora2b,27
    Tiempo2b,20
    Hora2c,29
    Tiempo2c,18]]
    
    local t = {}
    for k,v in data:gmatch("(%w-),([^%c]+)") do
       t[#t+1] = { k, v }
       print(k,v)
    end