Game Development Reference
In-Depth Information
'
The nil type is a special type that is equivalent in concept to C++
s NULL value,
although it behaves a bit differently. Any name that has never been used before is
considered to have a value of nil . This is also how you can delete objects from Lua.
print(type(y)) -- this will print
nil
y=20
print(type(y)) -- this will print
y = nil -- This effectively deletes y, causing the memory to be marked
-- for garbage collection
number
Attempting to Use a nil Value
C++
s nil are conceptually the same, but they behave very
differently. Most C++ compilers define NULL as 0. In Lua, nil has no value, it
only has a type. Be careful attempting to use nil as a valid value.
'
s NULL and Lua
'
Like most other programming languages, variables in Lua have scope. Unlike most
other programming languages, the default scope for Lua variables is global. That
means that even if you declare a variable inside of a function or if statement, it is
still considered a global variable. In order to make a variable local, you must explic-
itly use the local keyword:
local x = 10 -- this is a local variable
Variable Scoping in Lua
These scoping issues can really bite you if you
re not careful. You should always
declare a variable as local unless there is a real reason not to; otherwise, you
will find yourself with hard-to-fix bugs.
'
Variable Naming Conventions
Lua is a dynamically typed language, which means that it
s not always clear
what type a variable is intended to be. If you see a variable named
position , what do you think it is? Maybe it
'
'
s a 3D vector or a matrix or
even a custom table. It
s impossible to know without running the code and
inspecting the value. For these types of ambiguous variables, it
'
s often a good
idea to bake the type into the name. For example, the above variable could be
named positionVec3 or positionMat instead. This will save you a lot
more time than you might think.
'
 
Search WWH ::




Custom Search