Lua 學習筆記(八) ——實例(一)

學了幾天的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可以作爲數據結構來存儲文件。

發佈了49 篇原創文章 · 獲贊 30 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章