Trying to write to file

Posted by Fleagor on Thu 19 Mar 2009 02:47 AM — 3 posts, 12,252 views.

#0
Hello,

I have a trigger that fires off when the first line of an item identification comes up, and launches a script that I hoped would write the information to a file, up until a blank line. Here's what I'm using:

item_list = io.open("itemlist.txt", "a")

repeat
	line = io.read()
	item_list:write(line)
until line == ""

item_list:close()

Here's the error I'm getting:

Run-time error
Immediate execution
[string "Trigger: "]:5: bad argument #1 to 'write' (string expected, got nil)
stack traceback:
        [C]: in function 'write'
        [string "Trigger: "]:5: in main chunk

The file is created, but remains empty. I'm guessing it's a problem with reading in output from the world. What's the best way to pipe that data into a file?
Amended on Thu 19 Mar 2009 02:48 AM by Fleagor
Australia Forum Administrator #1
You can't use io.read to read from the output buffer. io.read reads from stdin, which is not really assigned to anything in a GUI application.

What I would do is, when the first line of your multi-line sequence arrives, clear a table, eg.


lines = {}


Then enable a trigger to capture the subsequent lines, until a blank line.

That trigger adds each line, eg.


table.insert (lines, "%0") -- insert another line


Then when you get the blank line which terminates it all, disable this trigger, and write the whole lot out, similar to what you have but instead of io.read, do:


for _, line in ipairs (lines) do
  item_list:write(line)
end --for

#2
Thanks! I think my original idea was to redirect io.stdout to the file, but then I couldn't think of how to point it back to the screen after, and it looks like I got way off track with that read function. Anyway, I found your inventory example in the FAQ, and combined with the changes you showed to the file writing loop, I'm pretty sure I'll have this up and running in no time.

I just wanted to say I'm really impressed with Mushclient, your presence in the forums, and the quality of your tutorials and responses. It's great to see.