Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read specific line using lua

Tags:

lua

I want to read a specific line in lua. I have the following piece of code, but it's not working according to my needs, can anybody help?

#!/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
like image 820
Usman Avatar asked Apr 08 '26 02:04

Usman


2 Answers

If you just need to read one line, creating a table of all lines is unnecessary. This function returns the line without creating a table:

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
like image 194
cyclaminist Avatar answered Apr 11 '26 14:04

cyclaminist


You can use io.lines for this. io.lines returns an iterator over the lines in the file. If you want to access a specific line, you will first have to load all the lines into a table.

Here's a function that pulls the lines of a file into a table and returns it:

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

You can index into the returned table to get the specified line.

like image 45
Paul Belanger Avatar answered Apr 11 '26 14:04

Paul Belanger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!