Difference between revisions of "Nil"

From OpenEUO
Jump to: navigation, search
m (Created page with "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 val...")
 
m
 
(2 intermediate revisions by the same user not shown)
Line 15: Line 15:
 
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.
 
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 f    = function() return 1,2 end
  local a,b,c = 1,1,1
+
local a,b,c = 1,1,1
  a,b,c = f()
+
a,b,c = f()
  print(type(c))
+
print(type(c))
 +
if c == nil then print('the value of c was 1, but now it's nil!')
  
  --> '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 ==
 +
 
 +
* [[...]]
 +
 
 +
* [[type]]
 +
 
 +
* [[tuple]]

Latest revision as of 19:58, 1 November 2010

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