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". If we implemented this by detouring the item.RegisterItem() function, we would make 3 items for every 1 item in the game. Moreover, if you had 3 addons that each did this, the number of items would quickly explode to an unmanageable number. In this tutorial, we'll look at another method of giving items effects. Instead of creating items with names, we're going to override how items save and load themselves to give them 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
|