@riidom: My advice, for what it's worth, would be not covering the OOP-like part. There is mo much to say about the raw use of tables,
so it might be better to dedicate an entire tutorial to the OOP topic.
@baconhawk7x:
The only one thing you start with:
Lua arrays (lists) starts at 1. Not 0.
It would be nice to introduce Lua's table.library.
Also, you can cover the different way to loop through a table: numeric for (in normal and reverse ways), ipairs, pairs. Be sure to talk about the
order in which they process the table key-element pairs.
You can also cover how one can get a table length (the count of elements) in a table using # operator (which is only valid for list-like arrays).
Maybe you can suggest a way to get that count in case the table is map-like:
Code: Select all
function count(t)
local nvalues = 0
for k,v in pairs(t) do nvalues = nvalues + 1 end
return nvalues
end
You can also cover sparse arrays (what happens when you loop through them). Also, It'll be nice to explain how Lua deals with nils in table, and the consequence on iterators, too. The great Ivan made a nice suggestion, how to remove safely elements in table while looping through (loop in reverse).
You can also explain what happens when passing a table to print-like function. And, oh well, explain how one can serialize a flat/simple table. For complex cases (nested tables, cyclic references, there are serialization libraries).
Also, similar to what the gret Riidom suggested first, it will be nice to explain that almost anaything can be used as keys in tables: numbers, strings, functions, tables, userdata.
Also, something that lots of people get confused with, the assignment operator does not produce a reference free copy of a table.
Code: Select all
local t = {}
local a = t -- a and t are references to the same object.
print(a, t)
In case one wants a reference copy, you can introduce a simple deep_copy function for flat tables:
Code: Select all
local function flat_copy(t)
local copy = {}
for k,v in pairs(t) do copy[k] = v end
return copy
end
After that, you can also introduce this new version which handles nested-arrays:
Code: Select all
local function nested_copy(t)
local copy = {}
for k,v in pairs(t) do
if type(v) == 'table' then
copy[k] = nested_copy(v)
else
copy[k] = v
end
end
return copy
end