This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
ardera's profile picture

How to copy variables

Started by ardera, 29 August 2012 - 10:42 AM
ardera #1
Posted 29 August 2012 - 12:42 PM
Hey,
Im working on an feature for my OS (see Signature ^^) that adds windows, (resizeable).
And the first thing i worked on was to replace the term.getSize function only for this program,
so i copied the os.run and the shell.run function and in the os.run function I added a code piece, that
copied the _G table
replaced the term.getSize function in the copied _G table

but it seems that the table are synchronized! When I replaced the term.getSize function in the copied _G table, my OS resized too!

Does anyone know a way to replace the function only in this table?
Or how to emulate a smaller terminal for this program?

I have really no idea how to do that…
Please help :)/>/>
KaoS #2
Posted 29 August 2012 - 02:33 PM
in order to copy a table without synchronising it with the original use this code


new_table={}
for k,v in pairs(original_table) do
new_table[k]=v
end
ardera #3
Posted 29 August 2012 - 08:48 PM
ah *testing*
EDIT: it didn't work.. it seems that you cant create an copy of _G?
Andybish #4
Posted 29 August 2012 - 09:07 PM
I looked on the LUA site, and underscored capitalized variables are locked as internal variables. Maybe this is something to do with it, I don't know.
Kingdaro #5
Posted 29 August 2012 - 09:43 PM
Try this:

local g = setmetatable( {}, {__index = _G} )
g being your local copy.
ardera #6
Posted 29 August 2012 - 09:49 PM
isn't then g a link to _G? *testing*

Didn't work…

God why you can't copy the _G table? Why?
Kingdaro #7
Posted 29 August 2012 - 09:57 PM
g is it's own table, however when you try to find a property of g it'll go to _G.

this is basically how OO in lua works.

If that doesn't work, there's a deepcopy function you can use.

g = deepcopy(_G)

It's probably the better way of doing this anyway, due to the fact that just indexing won't copy over all of _G's tables.
ardera #8
Posted 29 August 2012 - 10:19 PM
Yay it works! Thanks to Kingdaro for the deepcopy function!
KaoS #9
Posted 30 August 2012 - 07:36 AM
:)/>/> but that function essentially does the same thing, it just also copies metatables, does anyone know why mine did not work?
ardera #10
Posted 30 August 2012 - 07:57 AM
:)/>/> but that function essentially does the same thing, it just also copies metatables, does anyone know why mine did not work?
Change this

return setmetatable(new_table, getmetatable(object))
to this

return new_table

I don't know why, but then did mine work