lua-users home
lua-l archive

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


On Sun, Jul 24, 2011 at 1:56 PM, Gilles Ganault <gilles.ganault@free.fr> wrote:
> Hello
>
> Using a Lua script on XP, I need to open an HTML file and extract
> hyperlinks...
> ===========
> data = io.open("C:\places.txt","r")
> for line in data:lines() do
>      for token in string.gmatch(line, '<a
> href="(/places/.+?\.php)">') do
>              print(token)
>      end
> end
> data:close()
> ===========
>
> ... but it fails with the following error message:
> ===========
> lua5.1.exe: places.lua:2: attempt to index global 'data' (a nil value)
> ===========
>
> Any idea what is wrong with the above?

'data' is nil because io.open returns nil on failure. I would suggest
the following first line:

data = assert(io.open([[C:\places.txt]],"r"))

Note two things:
1) The call to assert to raise any error relating to not being able to
open the file.
2) Using [[...]]] instead of "...", as the filename contains slashes,
so either you need to escape each one ("C:\\places.txt") or use
[[...]] delimiters.