学了几天的lua,现在来学习一个例子。它将lua作为数据结构存在数据,然后将这些数据已HTML的方式展现出来,其结果是:http://www.lua.org/uses.html 这个网页。
首先写一个数据文件:db.lua
entry{
title = "Tecgraf",
org = "Computer Graphics Technology Group, PUC-Rio",
url = "http://www.tecgraf.puc-rio.br",
contact = "Waldemar Celes",
description = [[
Tecgraf is the result of a partnership between of Rio de Janeiro,
and <a HREF = "http://www.petrobras.com.br/">PRTROBRAS</a>,the
Brazilian Oil Company .
Tecgraf is Lua's birthplace,and the language has been used
there since 1993.
...
]]
然后,写调用这个文件的程序。
function fwrite(fmt,...) --fwrite函数
return io.write(string.format(fmt,...))
end
function writeheader() --固定的网页头
io.write([[
<html>
<head><title>Projectusing Lua</title></head>
<body bgcolor="#FFFFFF">
Here are brief description of some Projects around the world that use
<a href="home.html">Lua</a>.
<br>
]])
end
function entry1(o)
count = count + 1
local title = o.title or "(no title)"
fwrite('<li><a href="#%d">%s</a\n',count,title)
end
function entry2(o)
count = count + 1
fwrite('<hr>\n<h3>\n')
local href = o.url and string.format(' href="%s"',o.url) or ' '
local title = o.title or o.org or 'org'
fwrite('<a name="%d"%s>%s</a>\n',count,href,title)
if o.title and o.org then
fwrite('<br>\n<small><em>%s</em></small>',o.org)
end
fwrite('\n</h3>\n')
if o.description then
fwrite('%s<p>\n',
string.gsub(o.description,'\n\n+','<p>\n'))
end
if o.email then
fwrite('Contact: <a href="mailto:%s">%s</a>\n',
o.email,o.contact or o.email)
elseif o.contact then
fwrite('Contact: %s\n',o.contact)
end
end
function writetail() --网页尾部
fwrite('</body></html>\n')
end
local inputfile = 'D:/Lua Program/db.lua' -- db.lua的路径,我的是<span style="font-family: Arial, Helvetica, sans-serif;">D:/Lua Program/db.lua</span>
writeheader()
count = 0
f = loadfile(inputfile) --加载数据文件
entry = entry1
fwrite('<ul>\n')
f()
fwrite('<ul>\n')
count = 0
entry = entry2
f()
writetail()
执行结果:
这个例子是表示lua可以作为数据结构来存储文件。