Game Development Reference
In-Depth Information
function foo(bar, baz, faz)
local bar = bar or "Bar"
local baz = baz or "Baz"
local faz = faz or "Faz"
print("We got", bar, baz, faz)
end
Notice that we set the default values of variables by simply using or . A good idea is to use a local
variable with the same name.
Not only is this helpful in assigning default values to variables that are unassigned (i.e. are nil), but
local res = {}
for i, j in pairs(table 1) do
res[i] = j
end
return res
end
Please note that the preceding function is called a shallow copy , as it does not copy the embedded
tables, so if the table has any nested tables, those are not copied. To make an exact copy, we need
to perform what is called a deep copy .
Performing a Deep Copy
As mentioned in the preceding section, to completely create a copy of a table, we need to perform
a deep copy. This will copy all elements recursively and also set the metatables as required. Normal
copying does not set the metatable.
function deepcopy(t)
if type(t) ~= 'table' then
return t
end
local mt = getmetatable(t)
local res = {}
for k,v in pairs(t) do
if type(v) == 'table' then
v = deepcopy(v)
 
Search WWH ::




Custom Search