Hello,
I’m using Harlowe 3.3.7 in Twine, and I’m pretty new at writing code for this platform. I am trying to set up an inventory system where items can be accessed, added, removed, etc…
I have been trying to use a datamap to do this but keep running into errors with the macros I try. I’d like to be able to loop through the datamap and be able to access and change specific names (representing items) and values (representing cost) stored in it. I know that just calling the inventory’s var name will print its values but that’s not really my goal. Here’s an example of what I’ve tried so far:
(set: $inventory to (dm: "item a", 3, "item b", 2, "item c", 7, "item d", 4))
$inventory
<!--get number of pairs in a datamap-->
(set: $DMpairCount to (macro:datamap-type _datamap, [
(output-data: (dm-names: _datamap)'s length)]))
count of inventory pairs: ($DMpairCount: $inventory)
<!-- this works to get a name and value pair but i'm not sure how to access them both at once in a single macro -->
(print: (dm-names:$inventory)'s 1st)
(print: $inventory's (dm-names:$inventory)'s 1st)
<!-- NOT WORKING - this returns all of the names but should just print "item a" -->
(nth: 1, (dm-names:$inventory))
(set: $accessInv to (macro: dm-type _inv, [
(if: ($DMpairCount: $inventory) is not 0)[
(for: each _item, ...(dm-names:_inv))[
<!--If this worker, I would add code here to access the corresponding value of each item, and (see next code section) be able to change the values based on type of transaction-->
(output-data: _item)]](else:)[(output-data: "this inventory is empty")))]
]))
($accessInv: $inventory)
I’m just stuck and don’t know if what I’m trying to do is possible, although the concept seems simple to me. The code snippet below is an example of a different inventory system (for the player) which works and can handle addition and subtraction of values, but the difference is that it is an array instead of a datamap. Would using 2 sets of arrays (or more) for this other inventory system make more sense since macros like (count:) can only be used with with arrays? Or some other method entirely?
<!--code to update player inventory-->
(set: $updateInv to (macro: str-type _name,str-type _type, [
(if: $money is > 0)[(set: $inv to it + (a: "$money coins"))]
(if: _type is "add")[(set: $inv to it + (a: _name))
(output-data: _name)]
(else-if: _type is "sub")[(set: $inv to it - (a: _name))
(output-data: _name)
]
Thanks very much to anyone who might have some insight.