Lua实现正序和倒序的文件读取方法

--table 特性
-- 使用table生成正序和倒序的链表

-- 使用table生成链表

list = nil
local file = io.open("table.lua","r") -->打开本本件

pre = nil
--将本文件按行顺序读入list中
for line in file:lines() do  
	current = {next = nil,value = line}
	pre = pre or current
	list = list or pre
	pre.next = current
	pre = current
end

file:close() -- 关闭文件

-- 输出list
local l = list
while l do
	print(l.value)
	l = l.next
end

-- 以下是按行倒序的方法
print("以下是按行倒序输出文件:n")
local file = io.open("table.lua","r") -->打开本本件

list = nil --清空list之前的内容

for line in file:lines() do
	list = {next = list,value = line}
end

file:close() -- 关闭文件
-- 输出list
local l = list
while l do
	print(l.value)
	l = l.next
end