aboutsummaryrefslogtreecommitdiff
path: root/tutorials/tut031_metatables.md
diff options
context:
space:
mode:
authorAlexander Pickering <alexandermpickering@gmail.com>2017-11-26 21:07:54 -0500
committerAlexander Pickering <alexandermpickering@gmail.com>2017-11-26 21:07:54 -0500
commit83af51534bf16bf048aea1cd3b74a0308ed9dd71 (patch)
treeff82f3e6dd841633b1355b73181bcae607ee1138 /tutorials/tut031_metatables.md
parent25e4d04a331a6a0b9d897d4f721757730771ff97 (diff)
downloadartery-83af51534bf16bf048aea1cd3b74a0308ed9dd71.tar.gz
artery-83af51534bf16bf048aea1cd3b74a0308ed9dd71.tar.bz2
artery-83af51534bf16bf048aea1cd3b74a0308ed9dd71.zip
Started work on writing tutorials
Wrote tutorials for * Setup * Addon structure * Inventories * Items
Diffstat (limited to 'tutorials/tut031_metatables.md')
-rw-r--r--tutorials/tut031_metatables.md30
1 files changed, 30 insertions, 0 deletions
diff --git a/tutorials/tut031_metatables.md b/tutorials/tut031_metatables.md
new file mode 100644
index 0000000..a397cc9
--- /dev/null
+++ b/tutorials/tut031_metatables.md
@@ -0,0 +1,30 @@
+# Tut 0x031
+
+## Metatables
+
+In the last tutorial we saw how to make a simple inventory, but we used a function from Gmod's library that was a bit silly. When we made a copy of our inventory, we used table.Copy() to return a copy seperate to the version in the registry. There's nothing wrong with this, but if you have a lot of fields, and default tables in your inventory, this can get quite costly. There's a simple alternative, lua metatables.
+
+[Programming in Lua](https://www.lua.org/pil/13.html) does a much better job at explaining metatables than I ever could, so take a look at how they use it. We're not going to use all the features they discuss, just 1: the \_\_index method, to replace the DeSerialize() function from @{tut030_inventories.md}.
+
+ function inv:DeSerialize()
+ local self_copy = {}
+ local mt = {
+ __index = function(table,key)
+ return self[key]
+ end
+ }
+ setmetatable(self_copy,mt)
+ local json = util.JSONToTable(data)
+ for k,v in pairs(json) do
+ local item_name = v[1]
+ local item_data = v[2]
+ local item = item_registry.GetItemFromData(item_name,item_data)
+ self_copy.items[k] = item
+ end
+ for k,v in pair(self_copy.items) do
+ self_copy.weight = self_copy.weight + v.weight
+ end
+ return self_copy
+ end
+
+Making this change for our example inventory isn't really a big deal, since we don't have many functions, but it's easy to get to a point where it's beneficial to not copy all the fields of an inventory whenever you need to deserialize it.