首先用lua遍历目录:

 function getDirs(path)
local s = {}
function attrdir(p)                  
for file in lfs.dir(p) do
if file ~= "." and file ~= ".." then
local f = p .. file
local attr = lfs.attributes (f)
if attr.mode == "directory" then
table.insert(s, f)
attrdir(f .. "/")
else
table.insert(s, f)
end
end
end
end
attrdir(path)
return s
end

  然后将结果打包成JSON格式用于传递:

 function string2JSON(path)
local s = getDirs(path)
local cjson = require("cjson")
local sJson = cjson.encode(s)
return sJson
end

  最后用lwt后台输出到页面中:

 require "httpd"
require "lfs" request, args = ... function getDirs(path)
local s = {}
function attrdir(p)
for file in lfs.dir(p) do
if file ~= "." and file ~= ".." then
local f = p .. file
local attr = lfs.attributes (f)
if attr.mode == "directory" then
table.insert(s, f)
attrdir(f .. "/")
else
table.insert(s, f)
end
end
end
end
attrdir(path)
return s
end function string2JSON(path)
local s = getDirs(path)
local cjson = require("cjson")
local sJson = cjson.encode(s)
return sJson
end httpd.set_content_type("text/plain")
httpd.write(string2JSON(request.filedir))

【Lua】LWT遍历指定目录并输出到页面中-LMLPHP

05-11 21:53