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

Getfenv unexpected result

Started by EveryOS, 14 March 2018 - 04:15 PM
EveryOS #1
Posted 14 March 2018 - 05:15 PM
So I was playing around with getfenv and noticed something weird:
So the script I used was this:

local func
do
  local inf = 1/0
  local neginf = -inf
  local NaN = 0/0
  func = function()
	print("Special numbers:")
	print(inf)
	print(neginf)
	print(NaN)
  end
end
func()
sleep(2)
print("\nReiteration:")
print(getfenv(func).inf)
print(getfenv(func).neginf)
print(getfenv(func).NaN)
sleep(2)
setfenv(func, {inf=1/0, neginf=-1/0, NaN=0/0})
print("\nOne more time:")
print(getfenv(func).inf)
print(getfenv(func).neginf)
print(getfenv(func).NaN)

And the output was:

Special numbers:
inf
-inf
nan

Reiteration:
nil
nil
nil

One more time:
inf
-inf
nan

I was expecting this:

Special numbers:
inf
-inf
nan

Reiteration:
inf
-inf
nan

One more time:
inf
-inf
nan
Why is it instead printing nil?
Edited on 14 March 2018 - 04:15 PM
SquidDev #2
Posted 14 March 2018 - 05:23 PM
The environment functions operate on the global environment, not the local variables. func doesn't reference any global called inf - it references a local instead (well technically an upvalue, but let's ignore that for now). If you remove the local declarations, it'll work as expected:


inf = 1/0
func = function() print(inf) end

--# Using the normal environment
func() --# inf
print(getfenv(func).inf)) --# inf

--# Modifying the function's environment
getfenv(func).inf = 0
func() --# 0

--# Entirely changing the environment
setfenv(func, { inf = 1 })
func() --# 1

Note if you use local inf = 1/0 instead, none of this will work.
EveryOS #3
Posted 14 March 2018 - 05:35 PM
OK thx