Game Development Reference
In-Depth Information
Knowing the Index of an Element
When working with a table (array object), we can get the element if we know the index of the element
(e.g., if we have a list of names and we know that the fifth element is Jayant , then we can access it
as arrTable[5] ). However, there are cases when we would have no clue about the index, but might
know the value. If we wanted to know what element in the table has the value of Jayant , we can use
the indexOf function:
function indexOf(arrTable, theValue)
for i, j in pairs(arrTable) do
if j == theValue then
return i
end
end
end
This will also work for non-array tables, but the return value will not be a numeric index, but a key of
type string .
Determining Whether a Table Is an Array
There could be a scenario when you need to know if a table is a hash table or an array. We can
determine this because the # operator returns the number of elements in an array, whereas for a
table it returns 0 or the count of elements that it can determine as an array. A non-array table will be
one that has more elements than the # operator can return.
function isArray(arrTable)
return #arrTable == tableLen(arrTable)
end
Setting Default Values
If you have been developing with other languages, you might be used to checking for values and
ensuring that they are set, as missing values can cause errors. You may be familiar with something
like the following:
function foo(bar)
if bar == nil then
bar = "Untitled"
end
print("We got :", bar)
end
While working with Lua, this is not really an issue; we can get rid of all these conditional statements
like so
 
Search WWH ::




Custom Search