Fixed possible stack overflow when trying to clone an object.

This commit is contained in:
Robert Zenz 2015-02-15 17:37:30 +01:00
parent 4f30352e38
commit efc8be750a
2 changed files with 46 additions and 2 deletions

View File

@ -5,10 +5,50 @@ dofile("./utils/test.lua")
-- Load the file for testing.
dofile("./utils/tableutil.lua")
dofile("./utils/list.lua")
test.start("tableutil")
test.run("clone", function()
test.run("clone_list", function()
local list = List:new()
list:add(0, 1, 2, 3, 4, 5)
local clone = tableutil.clone(list)
test.equals(true, list ~= clone)
list:clear()
test.equals(false, clone == nil)
test.equals(6, clone:size())
test.equals(0, clone:get(0))
test.equals(1, clone:get(1))
test.equals(2, clone:get(2))
test.equals(3, clone:get(3))
test.equals(4, clone:get(4))
test.equals(5, clone:get(5))
end)
test.run("clone_object", function()
local object = {
table = {
something = "string"
},
value = 5,
action = function()
return true
end
}
local clone = tableutil.clone(object)
test.equals(true, object ~= clone)
test.equals(false, clone == nil)
end)
test.run("clone_table", function()
local original = {
int = 5,
string = "test",

View File

@ -46,7 +46,11 @@ function tableutil.clone(table)
local clone = {}
for key, value in next, table, nil do
clone[tableutil.clone(key)] = tableutil.clone(value)
if value ~= table then
clone[tableutil.clone(key)] = tableutil.clone(value)
else
clone[key] = value
end
end
setmetatable(clone, tableutil.clone(getmetatable(table)))