Nil

From OpenEUO
Jump to: navigation, search

nil is a lua keyword and valid value and specifies something that does not exist.

 local a = 1
 a = a + b
 --> 'Error: attempt to perform arithmetic on global 'b' (a nil value)'

If no value has been assigned to a variable, then it is of type 'nil'.

 local a
 print(type(a))
 --> 'nil'

If a function call returns no results and yet it is assigned to a variable, that variable is still nil. If a function returns fewer results than available assignment variables, the extra variables are set to nil.

local f     = function() return 1,2 end
local a,b,c = 1,1,1
a,b,c = f()
print(type(c))
if c == nil then print('the value of c was 1, but now it's nil!')
--> 'nil'
--> the value of c was 1, but now it's nil!

Confusingly, nil can be used as a return value.

local f = function return nil end
local a,b,c = 1,1,1
a,b,c = f()
print(type(a))
--> 'nil'

And also as a parameter.

local f = function(any) print(type(any)) end
f()
f(nil)
--> 'nil'
--> 'nil'

See Also