aboutsummaryrefslogtreecommitdiff
path: root/tutorials/tut042_too_many_items.md
blob: 9d95b00f0dc024ac66317cb257002acda69ab805 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Tut 0x042

## Too many items

In the last tutorial we saw how to create lots and lots of items. Sometimes, you think to yourself "that's way too many", and when you do, you simplify. Rougelike games have a tendency to have attributes associated with items. Commonly, "blessed", "normal", and "cursed". In this tutorial, we'll be using the technique discussed in @{tut021_detouring.md} to give every item one of these stats by overrideing @{item.lua.RegisterItem} the Serialize() and DeSerialize() methods to give every item a little extra data.


garrysmod/addons/artery\_rougelite/data/artery/global/item\_attributes.txt
	
	local itm = nrequire("item.lua")
	local log = nrequire("log.lua")
	
	local oldregister = itm.RegisterItem
	function itm.RegisterItem(itemtbl)
		local oldserialize = itemtbl.Serialize
		local olddeserialize = itemtbl.DeSerialize
		
		--Add a single character "b" "n" or "c" to an item's serialize to tell us if it's blessed, normal, or cursed
		function itemtbl.Serialize(self)
			local firstchar = "n"
			if self.attribute == 1 then
				firstchar = "b"
			elseif self.attribute == -1
				firstchar = "c"
			end
			return firstchar .. oldserialize(self)
		end
		--Note that we've added a "attribute" field to each item, which is 1 if blessed, -1 if cursed, and anything else is normal.
		function itemtbl.DeSerialize(self,data)
			local firstchar = string.sub(data,0,1)
			local rest = string.sub(data,1)
			olddeserialize(self,rest)
			if firstchar == "b" then
				self.attribute = 1
			elseif firstchar == "c" then
				self.attribute = -1
			elseif firstchar == "n" then -- Notice above, the item dosn't nessessarilly need a .attribute field.
				self.attribute = nil
			else
				log.error("Deserialized with unknown first character: " .. firstchar)
			end
		end
	end