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

Question to bios.lua -> os.run

Started by Sewbacca, 26 January 2017 - 03:16 PM
Sewbacca #1
Posted 26 January 2017 - 04:16 PM
Hey guys, i looked into the code of os.run.
Can anyone explain, why did he do this?


function os.run( _tEnv, _sPath, ... )
	local tArgs = { ... }
	local tEnv = _tEnv -- It just appears one time
	setmetatable( tEnv, { __index = _G } )
	local fnFile, err = loadfile( _sPath, tEnv )
	if fnFile then
		local ok, err = pcall( function()
			fnFile( table.unpack( tArgs ) ) -- Why not just pcall(fnFile, table.unpack(tArgs))
		end )
		if not ok then
			if err and err ~= "" then
				printError( err )
			end
			return false
		end
		return true
	end
	if err and err ~= "" then
		printError( err )
	end
	return false
end

Thanks in advance =)
Edited on 26 January 2017 - 05:34 PM
KingofGamesYami #2
Posted 26 January 2017 - 05:02 PM
It's a variable assignment.

If you want to know why: optimization.
SquidDev #3
Posted 26 January 2017 - 05:09 PM
If you want to know why: optimization.
What? No. The variable is already local so this has no effect on performance. Historically (5.0 or 4.*, I can't remember) there was a speed up of caching arguments, but this hasn't been true for a long time.

I don't know why it is there though, maybe a relic of Dan writing the function. It has been there since 1.41, quite possibly since the function was created.
Edited on 26 January 2017 - 04:09 PM
Sewbacca #4
Posted 26 January 2017 - 06:24 PM
If you want to know why: optimization.

Yeah i wanna knwo why (i don't think optimization, cause relative to reading the file, it doesn't matter)

And why don't just pcall(fnFile, table.unpack(tArgs))


-- Code taken from bios.lua and modified by Sewbacca
if type(_tEnv) ~= 'table' or type(_sPath) ~= 'string' then
  error('table environment, string path expected', 2)
end

    local tEnv = _tEnv
    setmetatable( tEnv, { __index = _G } )
    local fnFile, err = loadfile( _sPath, tEnv )
    if fnFile then
	    local ok, err = pcall(fnFile, ...)
	    if not ok then
		    return false, err
	    end
	    return true
    end
    return false, err
This should cause the exact same result (except of returning an error instead of printing it)
Edited on 26 January 2017 - 05:42 PM
KingofGamesYami #5
Posted 26 January 2017 - 11:28 PM
Completely missed that, was posting from my phone (bla bla bla school web filter). If it's not optimization then I can think of literally no reason to change the variable name.

I think what you are describing would have the result you want, but different people code different ways. Some people wouldn't immediately understand what "return pcall( fnFile, … )" means, whereas "return false, err" is pretty clear - it's going to return a boolean (false) and an error message (err).