lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


KHMan wrote:
> Arturo Amaldi wrote:
>> I am a relative newbie with regards to Lua. I am missing dearly the
>> presence of a scanf() facility -- I often have to deal with tables of
>> numbers written in exponential or floating point notation, and the use
>> of sscanf on a line iteration made it much easier to read in data. I
>> know i could use the "*number" format but I'd rather read the file
>> line by line and separate it afterwards.
> 
> As a Lua user, I'm glad I never have to touch scanf ever again.
> :-) Read and validate is always safer, I think.
> 
> Try using line iteration like the ref manual says:
> 
>     for line in io.lines(filename) do <body> end
>     for line in file:lines() do <body> end
> 
> Or something similar. Then use regular expressions to parse the
> line, perhaps using string.gmatch or something like that. A simple
> regex would be "[^,]+".

For simple file structures, standard Lua is quite readable and
brief. For line-based validation, it is relatively simple to
extend the format. For example, comment lines can be added very
easily. Here is an example, barely tested:

local dat = {}
local datfile = io.open("data.txt", "r")
if not datfile then error("bork!") end
for ln in datfile:lines() do
  if string.match(ln, "^#") then
    -- a comment line
  else
    local datln = {}
    for v in string.gmatch(ln, "[^,]+") do
      local n = tonumber(v)
      if not n then error("bork!") end
      datln[#datln + 1] = n
    end
    dat[#dat + 1] = datln
  end
end
datfile:close()

The above reads numbers into a data structure. For better
validation, the "[^,]+" regex can be changed to something more
specific.

-- 
Cheers,
Kein-Hong Man (esq.)
Kuala Lumpur, Malaysia