![]() |
|
[Lua/Help]Download file - Printable Version +- Sinisterly (https://sinister.li) +-- Forum: Coding (https://sinister.li/Forum-Coding) +--- Forum: Coding (https://sinister.li/Forum-Coding--71) +--- Thread: [Lua/Help]Download file (/Thread-Lua-Help-Download-file) |
[Lua/Help]Download file - 1llusion - 02-03-2011 Hi, so, recently I started to learn Lua Well... I'm beginner and I wanted to test somet, so I c/p a code from http://www.lua.org/pil/9.4.html Well.. I know it makes me a skid to c/p but well... I need sometimes something working to keep my interest ![]() Anyway... here is the code: Code: require "luasocket"
-- require "luasocket"
threads = {} -- list of all live threads
function get (host, file)
-- create coroutine
local co = coroutine.create(function ()
download(host, file)
end)
-- insert it in the list
table.insert(threads, co)
end
function download (host, file)
local c = assert(socket.connect(host, 80))
local count = 0 -- counts number of bytes read
c:send("GET " .. file .. " HTTP/1.0\r\n\r\n")
while true do
local s, status = receive(c)
count = count + string.len(s)
if status == "closed" then break end
end
c:close()
end
function receive (connection)
connection:timeout(0) -- do not block
local s, status = connection:receive(2^10)
if status == "timeout" then
coroutine.yield(connection)
end
return s, status
end
function dispatcher ()
while true do
local n = table.getn(threads)
if n == 0 then break end -- no more threads to run
local connections = {}
for i=1,n do
local status, res = coroutine.resume(threads[i])
if not res then -- thread finished its task?
table.remove(threads, i)
break
else -- timeout
table.insert(connections, res)
end
end
if table.getn(connections) == n then
socket.select(connections)
end
end
end
host = "site"
get(host, "/file")Now... the script doesn't seem to do its work for some reason, the require = "luasocket" gives error, so I guess I will need to add reference somehow ![]() Also, if it downloads, to what dirrectory? and how can I change it? Thanks alot!!! Have a great day! |