Page 1 of 1

[SOLVED] os.rename function causing crash

Posted: Thu Sep 27, 2018 1:06 pm
by DGM
I want to write a utility that creates some files and directories but places them into the same folder as the program rather than into the save directory. After some research I figured the easy way to do this was to create what I wanted in the save folder and then call os.rename to move it where I needed it. But the program I wrote to test the process isn't working.

Here's my code:

Code: Select all

require("os")

function love.load()
	fileName = "Test.txt"
	saveDir = love.filesystem.getSaveDirectory( )
	sourceDir = love.filesystem.getSourceBaseDirectory( )
	oldPath = saveDir.."/"..fileName
	newPath = sourceDir.."/"..fileName
end

function love.draw()
	love.graphics.print(oldPath, 100, 100)
	love.graphics.print(newPath, 100, 200)	
end

os.rename(oldPath, newPath)
When I comment out the os.rename line at the end I get the expected result (the source and destination paths are correctly shown). But the os.rename line itself gives the following error:

Code: Select all

Error

main.lua:17: bad argument #1 to 'rename' (string expected, got nil)


Traceback

[C]: in function 'rename'
main.lua:17: in main chunk
[C]: in function 'require'
[C]: in function 'xpcall'
[C]: in function 'xpcall'
Before you ask: yes, there is a Test.txt file waiting in the correct place.

Any idea what I'm doing wrong?

Re: os.rename function causing crash

Posted: Thu Sep 27, 2018 1:53 pm
by grump
You're using oldPath and newPath before anything has been assigned to them. LÖVE will read your main.lua file, execute top level code, and only after that love.load will be called.

[SOLVED] os.rename function causing crash

Posted: Thu Sep 27, 2018 2:37 pm
by DGM
[smacks forehead]

Right. Moving the string declarations out of the load function fixed it. Thanks.