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

Question about behaviour when overriding a global function.

Started by TurboTuTone, 12 July 2013 - 08:07 PM
TurboTuTone #1
Posted 12 July 2013 - 10:07 PM
Hello,

Recently when i had some defect code and started to put some prints to find the culteprit, i by accident stumbled on the following.

I have this override to fs.makeDir in my script:
local nativeMakeDir = fs.makeDir
function fs.makeDir(_sPath)
	print("MakeDir check: ",_sPath)
	if not fs.exists(_sPath) or fs.isDir(_sPath) then
		print("Making a dir")
		nativeMakeDir(_sPath)
		return fs.exists(_sPath) and true or false
	end
	return false
end

fs.makeDir("testing")

Now if you put that code in a file and run it once it prints the messages as expected.
However each time you run the file again its prints out the messages equal to the amount of times you have ran the file, as if the function is somehow called multiple times.
I suspect it might have something to do with the environments, but since i just started in lua/CC my knowledge is too limited to determine what is happening.

I was wondering if theres someone out there who could explain what exactly is going on here and also if possible how to prevent this.

Regards,
Turbo
ElvishJerricco #2
Posted 12 July 2013 - 10:45 PM
When your program closes, it does not restore nativeMakeDir to fs.makeDir. So after your program has finished running, the rest of the system is still using your makeDir function. Therefore, when you run your program again, the nativeMakeDir in this instance of your program references the makeDir created in the last instance, which still holds on to the real nativeMakeDir. So you're basically calling your print statements once for each time the program has run.

There are two solutions for this.
  1. You could restore fs.makeDir = nativeMakeDir at the end of your program. But then if someone terminates your program via ctrl+t, you remain screwed.
  2. You could create a new variable in the fs table to track whether your new makeDir has been created yet.
  3. 
    local nativeMakeDir = fs.makeDir
    if not fs.longName then
        function fs.makeDir(_sPath)
            ...
        end
    end
    fs.longName = true -- use a long, specific name there so that if someone
                       -- else uses this same technique, they are not likely
                       -- to use the same name as you.
    
TurboTuTone #3
Posted 12 July 2013 - 11:19 PM
Aah ofcourse, thanks for clearing that up and your solution :)/>
Implemented your fix, works like a charm.

Very much appreciated.