lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2013/3/1 Javier Guerra Giraldez <javier@guerrag.com>:
> On Thu, Feb 28, 2013 at 6:47 PM, Sven Olsen <sven2718@gmail.com> wrote:
>> By chaining ~, I can write statements like the following, which are safe
>> even when 'object' or any of it's subtables have a chance of being nil:
>>
>>   color = object~icon~glow~color or white
>
> you can change the metatable of nil to get that behavior.
>

I just had to try this out immediately. It is absolutely and totally brilliant.

There are two flavours.  To emphasize the difference, I have written
the metamethods out as individual functions.



first = function(a,b) return a end
second = function(a,b) return b end

the_table = first
the_key = second

object={icon={glow={color="blue"}}}
object1={icon={}}

return object.icon.glow.color or "white"
--> blue
return object1.icon.glow.color or "white"
--[[> stdin:1: attempt to index field 'glow' (a nil value)
stack traceback:
	stdin:1: in main chunk
	[C]: in ?
]]

debug.setmetatable(nil,{__index=the_table})
return object1.icon.glow.color or "white"
--> white

debug.setmetatable(nil,{__index=the_key})
return object1.icon.glow.color or "white"
--> color