Why when I program using Metatables
, and set 3 letters, access the main table then fire the function it only prints the first letter.
local tab={} local meta={ __index=function(a,b,c) rawset(a,b,c) return'a','b','c' end } setmetatable(tab,meta) newtab=tab[1] print(newtab) -- > a
When I try setting tab[2] or tab[3]
, it still prints a.
I think here you trying is to print a, b and c. I don't know if it was the self of the table the key and the value but whatever I write the other thing you can do, enjoy !
I change something but you can change it back and if you want to learn more with metatables, just go one wiki here
soo here the code for printting all thing:
local meta={ __index=function(a, b, c) --rawset(a, b, c) -- not need to do this they are already set. return {'a', 'b', 'c'} end } local tab = setmetatable({}, meta) newtab = tab[1] print(table.concat(newtab, ', '))-- a, b, c --or print(newtab[1]) --> a --or print(newtab[2]) --> b --or print(newtab[3]) --> c
or if you want to see what is the table Adress they key and the value of the table, do this:
local meta={ __index=function(self, key, value) --rawset(self, key, value) -- not need to do this they are already set. return {self, key, value} end } local tab = setmetatable({}, meta) newtab = tab[1] print(newtab[1], newtab[2], newtab[3]) -- 3 will be nil because no value is setting