Why does corona crash when I try to write to a log?

This is a key logger I created as a challenge and to get used to the new language. I did not write this code with malicious intent.

First, I’m not sure how to find the file I’m writing to. I’m going off an example I found off the Corona Documentation.

I wasn’t able to find anything explaining what ‘system.DocumentsDirectory’ points to. I simply assumed it pointed to the documents directory on my computer.

I’m fairly new to programming like this so you’ll probably see my code and think ‘gross’ but I’m open to learning new concepts so if you see anything that could and should be done differently let me know.

function WriteToFile(String) local path = system.pathForFile("R@T.txt", system.DocumentsDirectory) print("Path") -- Just to try and determine the origin of the crash local File, ErrorString = io.open(path, "W") print("File") if not File then print('File error: ' .. ErrorString) else print("else") File:write(String) io.close(File) end File = nil end function ReturnInput( Key ) if Key.phase == 'down' then print(Key.keyName) WriteToFile(tostring(Key.keyName)) end end Runtime:addEventListener('key', ReturnInput)

The code crashes at line 9 ‘io.open’

For the simulator, your system.DocumentDirectory can be found by going to the simulator’s File menu and “Show Project Sandbox”. 

For io.open() the “W” should be “w” and it means “write over any existing file”. You most likely want to open it for append, which is “a”.

Finally be very careful using generic names like string, table etc. Those are Lua classes and are easily written over. You’re safe at the moment because String and string are different variable names in Lua, but if you ever did: 

string = “Hello World”

you wouldn’t be able to access things like: string.len(), etc.

Rob

For the simulator, your system.DocumentDirectory can be found by going to the simulator’s File menu and “Show Project Sandbox”. 

For io.open() the “W” should be “w” and it means “write over any existing file”. You most likely want to open it for append, which is “a”.

Finally be very careful using generic names like string, table etc. Those are Lua classes and are easily written over. You’re safe at the moment because String and string are different variable names in Lua, but if you ever did: 

string = “Hello World”

you wouldn’t be able to access things like: string.len(), etc.

Rob