PDA

View Full Version : Linked Variables...



Blackfoot
August 22nd, 2015, 22:39
OK. So I ran into a new one today, I've been puttering with this lua code for several years now and I'm kinda shocked that I haven't run into this before.

I am working on explosion dice for my Champions Ruleset and what I 'want' to do is take the roll, copy it, manipulate the copy, then deliver the original roll. I have most of it working nicely but when I get back to delivering the original roll.. it seems that it was somehow linked to my copy.
Here's what I am doing (and I've tried a bunch of different ways to get around it to no avail):

function onDamage(rSource, rTarget, rRoll)
local aOriginalDice = rRoll.aDice;
local sOriginalDesc = rRoll.sDesc;
if rRoll.explosion then
local rExRoll = rRoll;
local nDice = #rExRoll.aDice;
local aDice = rExRoll.aDice;
local nInch = 0;
while nDice > 1 do
table.remove(aDice, nDice);
rExRoll.aDice = aDice;
nInch = nInch + 1;
rExRoll.sDesc = "Range ".. nInch .. "\""
rExMessage = ActionsManager.createActionMessage(rSource, rExRoll);
Comm.deliverChatMessage(rExMessage);
nDice = nDice - 1;
end
end
rRoll.aDice = aOriginalDice;
rRoll.sDesc = sOriginalDesc;
Debug.chat(rRoll); -- This reports the value of everything correctly (including sDesc) except that aDice now has less items in it.
....Apparently some variables are linked in 2 directions or something... or the code can only keep track of 1 table at a time.. or.. well I just don't know .. which is why I'm posting. I tried to do a search for linked variables.. but that didn't really come up with much. Any ideas as to what's going on here?

Blackfoot
August 22nd, 2015, 22:53
OK.. so I added this bit at the beginning and it seems to have sorted it out:
local aOriginalDice = {};
for _,v in ipairs(rRoll.aDice) do
table.insert(aOriginalDice, v);
end

Blackfoot
August 22nd, 2015, 22:58
It came out looking like this:
https://www.fantasygrounds.com/forums/attachment.php?attachmentid=10763

Moon Wizard
August 22nd, 2015, 23:10
Unless you are assigning a basic type (such as string or number), the Lua assignment operator just copies a reference, and does not create a copy of the data. This happens to me all the time when trying to copy tables.

I built a UtilityManager.copyDeep function in CoreRPG to handle most simple deep copy cases.

Cheers,
JPG

Blackfoot
August 23rd, 2015, 01:45
Thanks. I will definitely try and make use of that next time.