Page 2 of 2

Re: Color Constant Trick

Posted: Tue Jan 22, 2013 12:11 am
by xXxMoNkEyMaNxXx
I've had problems with this idea in the past where __index truncates my returned values, so I don't think this would work. It is a great idea though.

Re: Color Constant Trick

Posted: Tue Jan 22, 2013 1:46 am
by ejmr
xXxMoNkEyMaNxXx wrote:I've had problems with this idea in the past where __index truncates my returned values in the past, so I don't think this would work.
That sounds pretty strange. Do you (or anyone) have an example of code where __index causes this problem?

Re: Color Constant Trick

Posted: Fri Jan 25, 2013 5:42 am
by xXxMoNkEyMaNxXx

Code: Select all

local met={"lol",1,true}
function met:__index()
	return unpack(self)
end
setmetatable(met,met)
print(met.asdf)
Output:
>lol

Re: Color Constant Trick

Posted: Fri Jan 25, 2013 5:57 am
by markgo
From the Lua manual, it's implied that __index returns one value because of the parentheses.

Code: Select all

 "index": The indexing access table[key].

     function gettable_event (table, key)
       local h
       if type(table) == "table" then
         local v = rawget(table, key)
         if v ~= nil then return v end
         h = metatable(table).__index
         if h == nil then return nil end
       else
         h = metatable(table).__index
         if h == nil then
           error(···)
         end
       end
       if type(h) == "function" then
         return (h(table, key))     -- call the handler
       else return h[key]           -- or repeat operation on it
       end
     end


Re: Color Constant Trick

Posted: Fri Jan 25, 2013 6:02 am
by xXxMoNkEyMaNxXx
LOLWHY

Re: Color Constant Trick

Posted: Fri Jan 25, 2013 6:23 am
by markgo
The only logic I can think of is that it keeps the behavior of returning values consistent whether it's a function or a simple index.

Re: Color Constant Trick

Posted: Fri Jan 25, 2013 10:22 am
by bartbes
Why? Well, because it determines "the value" of a variable, which is always singular. Imagine how confusing it would be if your variable contained more than one thing.

Re: Color Constant Trick

Posted: Sat Jan 26, 2013 4:17 pm
by ejmr
xXxMoNkEyMaNxXx wrote:

Code: Select all

local met={"lol",1,true}
function met:__index()
	return unpack(self)
end
setmetatable(met,met)
print(met.asdf)
Output:
>lol
That is awful and you are an awful person for writing it.

Heh, no I'm kidding. Thanks to you and bartbes for the example and explaining why it works the way it does. I have not used __index() in conjunction with unpack() before, but that's good to know for the future.