Page 1 of 1
Creating an exact copy of an object
Posted: Tue Nov 21, 2023 5:30 pm
by Kopelat
Is there a way to clone an object and possibly modify properties of it in lua?
In Roblox Lua it's just a function :Clone() but i don't know if there is one for normal lua
Do i need to make that function myself?
Re: Creating an exact copy of an object
Posted: Tue Nov 21, 2023 9:29 pm
by MrFariator
There are clone functions for a couple of specific types of things in löve, like
Source:clone for audio sources. However, based on what I can surmise from
Roblox documentation, you're asking for a method to create copies of lua objects. There is no readily available built-in functionality for this, in either lua or löve.
What sort of cloning were you thinking of? Maybe you are simply looking for object orientation (ie. implement some way to define classes, and easily create instances of said classes), which can be implemented with libraries like
classic and
middleclass.
However, if you want an
exact copy, then you could use the following function:
Code: Select all
local function copy (o, seen)
seen = seen or {}
if o == nil then return nil end
if seen[o] then return seen[o] end
local no
if type(o) == 'table' then
no = {}
seen[o] = no
for k, v in next, o, nil do
no[copy(k, seen)] = copy(v, seen)
end
setmetatable(no, copy(getmetatable(o), seen))
else -- number, string, boolean, etc
no = o
end
return no
end
When you pass a table to this function, it will return a copy of the table. Works on most simple tables. Wouldn't recommend this for creating instances of objects (like what Instance:clone is used for in roblox), but it can work when you need to copy or juggle some data around, without modifying the original table.
Re: Creating an exact copy of an object
Posted: Fri Nov 24, 2023 3:00 pm
by dusoft
Check the manual, deep copies are possible:
http://lua-users.org/wiki/CopyTable
Re: Creating an exact copy of an object
Posted: Fri Nov 24, 2023 4:07 pm
by MrFariator
The function I already posted handles deep copies, but it's not the only implementation to do so. The main caveat is that it may not work on tables that have any sort of special metatables going on, or extremely deep tables.
However, based on the roblox docs, I believe Kopelat might just need to look into simple object orientation, or maybe even ECS, since these deep table copy functions rely on recursion. That doesn't necessarily scale the best, for any sufficiently complex class.
Re: Creating an exact copy of an object
Posted: Sat Nov 25, 2023 7:43 pm
by darkfrei
Maybe it will be nice to have a entity prototype, that contents the same values in the entity, that have values that are unique for each entity.