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可以作为数据结构来存储文件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值