Advertisement
fatboychummy

Deepcopy environment

Feb 8th, 2024
941
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.66 KB | None | 0 0
  1. --- Deep copy function, we need to make a bit custom so we can handle loops.
  2. ---@param t table The table to deep copy.
  3. ---@param lookup table? Initializes the lookup table to something else.
  4. ---@return table clone The clone of the table.
  5. ---@return table lookup The lookup table built from deep copying the environment.
  6. local function deep_copy(t, lookup)
  7.   lookup = lookup or {}
  8.  
  9.   -- If the value we are copying is not a table, we can just return it.
  10.   if type(t) ~= "table" then
  11.     return t, lookup
  12.   end
  13.  
  14.   -- If we have already copied this table, we can just return the copy we have
  15.   -- already made.
  16.   if lookup[t] then
  17.     return lookup[t], lookup
  18.   end
  19.  
  20.   -- Create a new table to copy into.
  21.   local copy = {}
  22.  
  23.   -- Add the copy to the lookup table so we can handle loops.
  24.   lookup[t] = copy
  25.  
  26.   -- Copy the table.
  27.   for k, v in pairs(t) do
  28.     copy[deep_copy(k, lookup)] = deep_copy(v, lookup)
  29.   end
  30.  
  31.   return copy, lookup
  32. end
  33.  
  34. --- Copy the environment
  35. ---@param env table The environment to copy.
  36. ---@param g table The global environment to copy.
  37. ---@return table clone_env The clone of the environment.
  38. ---@return table clone_g The clone of the global environment, probably not needed as it will be the clone_env._G, but it's here for consistency.
  39. local function deepcopy_environment(env, g)
  40.   -- We need to copy the environment and the global environment separately.
  41.   -- We keep the lookup table between clones so we can handle loops.
  42.   local clone_env, lookup = deep_copy(env)
  43.   local clone_g = deep_copy(g, lookup)
  44.  
  45.   return setmetatable(clone_env, {__index = clone_g}), clone_g
  46. end
  47.  
  48. local cloned_env = deepcopy_environment(_ENV, _G)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement