方法1
–在一个死循环中设置一个跳出条件,但是这样的做法会占用大量CPU资源,强烈不推荐使用哦
function sleep(n) local t0 = os.clock() while os.clock() - t0 <= n do end end
方法2
–调用系统的sleep函数,不消耗CPU,但是Windows系统中没有内置这个命令(如果你又安装Cygwin神马的也行)。推荐在Linux系统中使用该方法
function sleep(n) os.execute("sleep " .. n) end
方法3
–虽然Windows没有内置sleep命令,但是我们可以稍微利用下ping命令的性质
function sleep(n) if n > 0 then os.execute("ping -n " .. tonumber(n + 1) .. " localhost > NUL") end end
方法4
–使用socket库中select函数,可以传递0.1给n,使得休眠的时间精度达到毫秒级别。
require("socket") function sleep(n) socket.select(nil, nil, n) end
用lua访问http
方法一:使用luasocket
需要luasocket。 下载地址: http://files.luaforge.net/releases/luasocket/luasocket
local http = require("socket.http") local ltn12 = require("ltn12") function http.get(u) local t = {} local r, c, h = http.request{ url = u, sink = ltn12.sink.table(t)} return r, c, h, table.concat(t) end url = "http://www.baidu.com" r,c,h,body=http.get(url) if c~= 200 then return end print(body)
方法二:借助系统curl
function get(url) local handle = io.popen("curl -q -k -s " .. url) local result = handle:read("*a") handle:close() return result end function post(url , fields) local handle = io.popen("curl -q -k -s -m 1 ".. url .. "-d" ..fields .. "`") local result = handle:read("*a") handle:close() return result end
lua之使用json
方法一:用lua的cjson包:
下载地址在这里 http://www.kyne.com.au/~mark/software/lua-cjson.php
安装的话,make&make install就行了。local cjson = require("cjson") local str = '["a", "b", "c"]' local j = cjson.decode(str) for i,v in ipairs(j) do print(v) end str = '{"A":1, "B":2}' j = cjson.decode(str) for k,v in pairs(j) do print(k..":"..v) end j['C']='c' new_str = cjson.encode(j) print(new_str)