Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --- Deep copy function, we need to make a bit custom so we can handle loops.
- ---@param t table The table to deep copy.
- ---@param lookup table? Initializes the lookup table to something else.
- ---@return table clone The clone of the table.
- ---@return table lookup The lookup table built from deep copying the environment.
- local function deep_copy(t, lookup)
- lookup = lookup or {}
- -- If the value we are copying is not a table, we can just return it.
- if type(t) ~= "table" then
- return t, lookup
- end
- -- If we have already copied this table, we can just return the copy we have
- -- already made.
- if lookup[t] then
- return lookup[t], lookup
- end
- -- Create a new table to copy into.
- local copy = {}
- -- Add the copy to the lookup table so we can handle loops.
- lookup[t] = copy
- -- Copy the table.
- for k, v in pairs(t) do
- copy[deep_copy(k, lookup)] = deep_copy(v, lookup)
- end
- return copy, lookup
- end
- --- Copy the environment
- ---@param env table The environment to copy.
- ---@param g table The global environment to copy.
- ---@return table clone_env The clone of the environment.
- ---@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.
- local function deepcopy_environment(env, g)
- -- We need to copy the environment and the global environment separately.
- -- We keep the lookup table between clones so we can handle loops.
- local clone_env, lookup = deep_copy(env)
- local clone_g = deep_copy(g, lookup)
- return setmetatable(clone_env, {__index = clone_g}), clone_g
- end
- local cloned_env = deepcopy_environment(_ENV, _G)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement