LUA Utility Functions: Difference between revisions

From SkyCorp Global
Jump to navigation Jump to search
(Created page with "Useful functions")
 
No edit summary
Line 1: Line 1:
Useful functions
Useful functions
== Clone / Deep Copy ==
Useful for making a copy of the object.  See the OOP example object for it in action.
<syntaxhighlight lang="lua">
function clone (t) -- deep-copy a table
  if type(t) ~= "table" then return t end
  local meta = getmetatable(t)
  local target = {}
  local keys = table.keys(t);
  io.write("Keys array is: " .. type(keys) .. "\n");
  io.write("Keys length is: " .. #keys .. "\n");
  for i=1, #keys do
      local key = keys[i];
      local value = t[key];
      io.write("Key: " .. key .. "\n");
      if key == "__metatable" then
        -- do nothing, metatable is handled separately (how to make lua not complain about empty if's?)
      elseif type(value) == "table" then
        target[key] = clone(value)
      else
        target[key] = value
      end
  end
  setmetatable(target, meta)
  return target
end
</syntaxhighlight>

Revision as of 05:30, 21 December 2017

Useful functions

Clone / Deep Copy

Useful for making a copy of the object. See the OOP example object for it in action.

function clone (t) -- deep-copy a table
   if type(t) ~= "table" then return t end
   local meta = getmetatable(t)
   local target = {}

   local keys = table.keys(t);

   io.write("Keys array is: " .. type(keys) .. "\n");
   io.write("Keys length is: " .. #keys .. "\n");

   for i=1, #keys do
      local key = keys[i];
      local value = t[key];
      io.write("Key: " .. key .. "\n");

      if key == "__metatable" then
         -- do nothing, metatable is handled separately (how to make lua not complain about empty if's?)
      elseif type(value) == "table" then
         target[key] = clone(value)
      else
         target[key] = value
      end
   end
   setmetatable(target, meta)

   return target
end