Game Development Reference
In-Depth Information
Here's an example of the function in use:
local boys = 5
local girls = 3
local className = "Math"
print("Boys:", boys, "Girls:", girls, "Class:", className)
printf("There are %d boys and %d girls in the %s class", boys, girls, className)
Counting the Number of Elements in a Table
Tables were introduced in Chapter 2. Tables that are stored as arrays can return the number of
# (length-of) operator. But when dealing with tables that are not arrays or a
local count = 0
for i,j in pairs(theTable) do
count = count + 1
end
return count
count variable, and then return
the count value as a result.
Using IsEmpty
Sometimes, you want to know if a variable is empty. But the definition of empty depends on the type
of variable it is. A numeric variable holding a zero value would be considered empty, a string with no
characters would be empty, a table with no elements would be empty, and all of these, if nil , could
also be considered empty. We can use the function tableLen (which we just created in the preceding
example) to determine the length of a table-type variable.
function isEmpty(var)
if var == nil then return true end
local varType = type(var)
if varType == "number" and var == 0 then
return true
elseif varType == "string" and #var == 0 then
return true
elseif varType == "table" and tableLen(var)==0 then
return true
end
return false
end
 
Search WWH ::




Custom Search