Original Post
I think my language terminology is failing me here so I'll let my code talk I want anything passed into my function as an argument to stay constant. I don't want the function to change it.
--[[
Function: NoReplacePick
Randomly pick from an array without replacement.
a = {1, 2, 3, 4, 5};
NoReplacePick(a) -> 2, {1, 3, 4, 5};
Parameters:
pickTable - The table that we randomly pick from.
Returns:
pick - Element picked.
modified pick table - pickTable with pick removed.
--]]
function NoReplacePick(pickTable)
--Choose a random number from 1 to pickTable length
local r = math.random(table.getn(pickTable));
--Swap first pickTable entry with another random entry
pickTable[1], pickTable[r] = pickTable[r], pickTable[1];
--Pick without replacement the first element in pickTable
local pick = pickTable[1];
table.remove(pickTable, 1);
--Return pick and modified pickTable
return pick, pickTable;
end
Now if I have:
a = {1,2,3,4,5}; --5 elements
pickTable(a);
-- a has 4 elements I want it to remain 5
Is there a special keyword I can use so it makes a copy rather than uses a reference? I tried making a local pickTableTemp variable than assigned pickTable to it (pickTableTemp = pickTable). I did this at start of the function and then only made reference to pickTableTemp but I had the same results. My searches haven't been much use because I'm not sure which words to use :( Any help would be appreciated. [Edited by - Balaam on August 30, 2005 4:58:01 AM]