Game Development Reference
In-Depth Information
Merging Two Tables
If you need to merge two tables, you can do so using
function mergeTables(table 1, table 2)
for i,j in pairs(table 1) do
table 2[i] = j
end
end
Note that if you have array values, the values in table 2 will overwrite these.
for i,j in pairs(theTable) do
if j == theValue then
return true
end
end
return false
Finding the Difference Between Two Tables
In your game, you might have the player collect items, so that you can display the items collected at
the end of the level. But you might also want to display the items that the could have collected but
did not. An easy way to do so is to use two tables—one with the items collected and one with all of
the items that could have been collected. Then, using the following function, you can determine the
items that exist in table 2 but not in table 1:
function differenceOfTables(table1, table2)
local res = {}
for i, j in pairs(table1) do
if not isValueInTable(j,table2) then
table.insert(res, j)
end
end
end
Getting a Return Value As a Table
In some cases you expect to get a table, but if the return value is a number or a string, it just breaks
your code and causes errors. You can ensure that you get returned a table value with the following:
function getTable(theValue)
if type(theValue) == "table" then
 
Search WWH ::




Custom Search