I was coding changing equipment on your character. Because I store equipment data as structs, it seemed straightforward enough: Create a "swap placeholder" equipment variable and then do this:
Swap placeholder = player's current equipment
Player's current equipment = new equipment
New equipment's slot (the equipment inventory is stored as an array) = swap placeholder
However, this did not work and I quickly realized why: My structs contain strings, and when I use the "=" operator to copy structs, it just copies the pointers of the strings over. I thought of 2 possible solutions:
(1) Write a crapton of tedious, repetitive code to manually copy all the data, accounting for all possible combinations of new and old equipment; or
(2) Write a function that takes 2 equipment structs as parameters and copies the old into the new, and just call this function a few times.
Option (2) is better than option (1) from pretty much any standpoint, but I soon realized another problem. Since my equipment is structs and not objects, by default, they get passed into a function by value and not by reference. This means they become local variables and any changes made to them don't affect the original structs, thus defeating the whole purpose of the exercise. The solution, obviously, is to pass in the addresses of the structs and dereference them in the function, but I had no idea how to pass structs by reference in Objective-C and couldn't really figure it out.
...Then I remembered that Objective-C is a proper superset of C.
So I went back into my raw-C DataTypes header file and added my copyEquipment method signature to that in C format, then wrote the function definition in my Objective-C source file (which looks weird packed in between my Objective-C functions because the signature syntax is completely different), and used the "->" dereference operator to assign values to the struct members while retaining the memory address of the original struct. But, since the string members are still Objective-C objects, I had to combine the C dereference with the Objective-C signals. Then I went back and replaced my original copying code with calls to the copyEquipment function using the "&" address-of operator (after fetching the relevant equipment out of the inventory array).
...Then it worked.
It's very rare that I actually have reason to use the -> and & C operators, so that was actually kinda fun.
Whee.
- Satellite Observatory (James)


No comments:
Post a Comment
Note: Only a member of this blog may post a comment.