4

I'm new with lua but working on an application that works on specific files with given path. Now, I want to work on files that I download. Is there any lua libraries or line of codes that I can use for downloading and storing it on my computer ?

websteerr
  • 41
  • 1
  • 2

1 Answers1

7

You can use the LuaSocket library and its http.request function to download using HTTP from an URL.

The function has two flavors:

  • Simple call: http.request('http://stackoverflow.com')
  • Advanced call: http.request { url = 'http://stackoverflow.com', ... }

The simple call returns 4 values - the entire content of the URL in a string, HTTP response code, headers and response line. You can then save the content to a file using the io library.

The advanced call allows you to set several parameters like HTTP method and headers. An important parameter is sink. It represents a LTN12-style sink. For storing to file, you can use sink.file:

local file = ltn12.sink.file(io.open('stackoverflow', 'w'))
http.request {
    url = 'http://stackoverflow.com',
    sink = file,
} 
Michal Kottman
  • 16,375
  • 3
  • 47
  • 62
  • getting the following with the `local file` statement: `attempt to index local 'file' (a function value)` – crockpotveggies Aug 15 '16 at 21:05
  • 1
    @crockpotveggies please post full source code (somewhere like pastebin) that is failing you, together with the version of luasocket, since the short snippet in this answer works as intended. – Michal Kottman Aug 21 '16 at 17:40