Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Setting Metatables Problem?

Asked by
woodengop 1134 Moderation Voter
8 years ago

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.

0
Metamethods in Lua 5.1 are limited to returning only 1 value; hence, 'b' and 'c' will not be returned unless, as xToonLinkX123 stated, you pack all values you want to return into an array. Goulstem 8144 — 8y

1 answer

Log in to vote
1
Answered by 8 years ago

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
Ad

Answer this question