使用lua读取特定行

使用lua读取特定行,lua,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) specifi

我想读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
你可以用这个
io.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

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

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

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

改进的格式和拼写要读取整个文件,请使用
contents=file:read(“*a”)
。我想读取特定的行。就像在代码里一样,我想读第二行。