This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
AnDwHaT5's profile picture

How to write and read a specific line

Started by AnDwHaT5, 30 June 2013 - 09:09 AM
AnDwHaT5 #1
Posted 30 June 2013 - 11:09 AM
So i am making a rpg game and i am using s = fs.open("saves", "w"). I am putting in numbers for coords such as when i hit the up button or "200" as a raw key event it does some math on y taking away 1. What i want my program to do is write in the file saves being the first line as the x coord and the second line as the y coord and then the program reading that and then plugging that into the term.setCursorPos(a, B)/> a is the final version of y and b is the final version of x. I use them to do that math such as a = y+1 or b= x+1. That way variables dont get screwed up by using x and y.


Here is my current code.


q = 1
x = 5
y = 5
term.setCursorPos(x,y)
print("@")
while true do
local event, p1 = os.pullEvent("key")
if p1 == 200 then
a = y-q
term.setCursorPos(x,a)
s = fs.open("saves", "w")
s.write(a)
s.close()
term.clear()
print("@")
end
end

and the pastebin id is VR7L6vcK
Apfeldstrudel #2
Posted 30 June 2013 - 12:46 PM
Can a key event be 200? Wouldn't the event trigger before you write 00?
Also, you might wanna quote the 200 in the if statement
AnDwHaT5 #3
Posted 30 June 2013 - 12:58 PM
yes it can be 200 it is the up arrow and the code works fine right now i just need this info and i will be able to make a unlimited movment space.
Engineer #4
Posted 30 June 2013 - 02:11 PM
Not quite sure what you mean, but if you wand to write on different lines:


local f = fs.open( "saves", "a" )
f.writeLine("This is the first line")
f.writeLine("This is the second line")
f.close()

If you want to read line by line:

local f = fs.open( "saves", "r" )
-- Option 1:
local lines = {} --# this is just handy to have it in a table
for line in f.readLine do
   table.insert( lines, line )
end

-- Option 2:
local firstLine = f.readLine()
local secondLine = f.readLine()

f.close()

I recommend the first option if you want to read a specific line, because then you have everthing in the table and you can easily look it up.
AnDwHaT5 #5
Posted 30 June 2013 - 02:48 PM
Ok i got that but it is ssaying that it expects a number. I dont need huge specifics in case of lines just to know line 1 is x and line 2 is y. But when i plug it in to the term.setCursorPos it says expecting number or something. It isnt using the variable. here is the current code.
local f = fs.open( "saves", "r")
b = f.readLine()
a = f.readLine()
f.close()
term.setCursorPos(b,a)
print("@")
while true do
local event, p1 = os.pullEvent("key")
if p1 == 200 then
a = y-q
term.setCursorPos(x,a)
local f = fs.open( "saves", "a")
f.writeLine(a)
f.writeLine(B)/>
f.close()
term.clear()
print("@")
end
end
AnDwHaT5 #6
Posted 30 June 2013 - 03:18 PM
Nvm i got it. Thank you.