使用lua读取特定行

时间:2018-05-02 09:30:22

标签: lua

我想在lua中读取一个特定的行。我有以下代码,但是根据我的需要它没有工作,有人可以帮忙吗?

#!/usr/bin/env lua

local contents = ""
local file = io.open("IMEI.msg", "r" )
if (file) then
   -- read all contents of file into a string
   contents = file:read()
   file:close()
   print(contents)
   specific = textutils.unserialize(contents)
   print(specific[2])
else
   print("file not found")
end

2 个答案:

答案 0 :(得分:3)

如果您只需要读取一行,则无需创建所有行的表。此函数返回行而不创建表:

function get_line(filename, line_number)
  local i = 0
  for line in io.lines(filename) do
    i = i + 1
    if i == line_number then
      return line
    end
  end
  return nil -- line not found
end

答案 1 :(得分:2)

您可以使用io.linesio.lines在文件中的行上返回一个迭代器。如果要访问特定行,首先必须将所有行加载到表中。

这是一个将文件的行拉到表中并返回它的函数:

function get_lines(filename)
    local lines = {}
    -- io.lines returns an iterator, so we need to manually unpack it into an array
    for line in io.lines(filename) do
        lines[#lines+1] = line
    end
    return lines
end

您可以索引返回的表以获取指定的行。

相关问题