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

need help with metatables

Started by JokerRH, 12 February 2013 - 12:46 PM
JokerRH #1
Posted 12 February 2013 - 01:46 PM
I recently learned basics about metatables in lua.
My problem is that i can only insert a metatable into anotherone
with it's metatable.
I hope the example can show my problem better:


t = {}
t = setmetatable({}, t)

s = {}
s = setmetatable({test = "test"}, s)

table.insert(t, s)

therefore t[1].test returns "test".
now, if i change s:


s.test = "asdf"

t[1].test also returns "asdf".
Is there a way to prevent that instead of changing these to normal tables?
(I need both of them as metatables for the rest of my apis)

thanks. :)/>/>

Edit: This means that i need a method like getmetatable to get back the table that has the metatable attached to it (if such a method exists)
tesla1889 #2
Posted 12 February 2013 - 06:47 PM
i think you arent understanding the concept of metatables. metatables are tables of functions to be used by the object they define

using the syntax:

object:metamethod()

and getmetatable does exist

it just wont work if the table has a __metatable index
immibis #3
Posted 12 February 2013 - 07:14 PM
i think you arent understanding the concept of metatables. metatables are tables of functions to be used by the object they define

using the syntax:

object:metamethod()

and getmetatable does exist

it just wont work if the table has a __metatable index
I don't think you're understanding them either.
tesla1889 #4
Posted 12 February 2013 - 08:06 PM
i think you arent understanding the concept of metatables. metatables are tables of functions to be used by the object they define

using the syntax:

object:metamethod()

and getmetatable does exist

it just wont work if the table has a __metatable index
I don't think you're understanding them either.

thats how you use them

i mean, there are library defined functions that you can set, but he probably wont need any of those
Eric #5
Posted 12 February 2013 - 09:07 PM
Your meteta les are irrelevant here. What you're seeing is standard pass-by-reference behaviour for tables.


t = {}
s = {test = "test"}

table.insert(t, s)
s.test = "changed"

print(t[0].test)
JokerRH #6
Posted 12 February 2013 - 10:10 PM
yes, I think that I do understand the way metatables work, I just thought that this
was a sideeffect of them and therefor made an example that only defined it and inserted
it into anotherone. I didn't even think that this was a normal table's behaviour…:(/>
(thanks Eric!)