Search code examples
stringlualua-table

Save io.read() file reading result to a string


So I have some code:

  io.input(file)

  print(io.read())
  
  result = io.read()
  print(result)

  io.close(file)

and when I run this, I get

dasdasd
nil

where "dasdasd" is the content of the file. This signifies to me that the result of io.read() was not properly not saved to the string. Why is this the case? What am I missing?


Solution

  • You're assuming read() goes back to the beginning each time. This would require a seek() operation to be performed. https://pgl.yoyo.org/luai/i/file%3Aseek

    f  = io .input( 'filename.txt' )
    print( f :read() )
    
    f :seek('set')  --  set returns to the beginning
    result  = f :read()
    print( result )
    
    f :close()