Lua 读取文件指定行数

测试文件: TestReadFile.txt
在这里插入图片描述
Lua 代码

-- 打印 table 函数
function printTable(datas,title)
    title = title or "";
    print("printTable  length: "..#datas.." |"..title);
    for k,v in ipairs(datas) do
        print(v);
     end  
end   

--打印函数 打印所有参数
function pf(fmt,...)
	fmt = fmt or ""
	local args = table.pack(...)
	local argsNum = args.n
	if argsNum <= 0 then
		return print(fmt)
	end
	fmt = tostring(fmt)
	local argStr = ""
	for i = 1,argsNum do
		argStr = string.format("%s arg%s:%s ",argStr,i,tostring(args[i]))
	end
	print(fmt..argStr)
end

----------------------------------------------
-- 读取文件指令行 -1代表最后一行
local readFileByLineIndex = function(fileName,readLineIndex)
	fileName = fileName or "TestReadFile.txt" 
	readLineIndex = readLineIndex or 1
	local file = assert(io.open(fileName,"r"))
	local contentTable = {
    
    }
	local lineIndex = 1
	local fileLastIndex = 1
	for line in file:lines() do
		contentTable[lineIndex] = line
		lineIndex = lineIndex + 1
	end
	--printTable(contentTable,fileLastIndex)
	fileLastIndex = lineIndex - 1
	if readLineIndex > fileLastIndex then
		readLineIndex = fileLastIndex	
	end
	if readLineIndex == -1 then
		pf("最后一行:",contentTable[fileLastIndex])
	else
		pf("读取行数",readLineIndex,contentTable[readLineIndex])
	end
	file:close()
end

readFileByLineIndex(nil,-1)
readFileByLineIndex(nil,2)


结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_32756581/article/details/129231386
LUA