[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Safe navigation operator
- From: Wesley Smith <wesley.hoke@...>
- Date: Mon, 23 Aug 2010 14:17:08 +0200
> So the next step was "Well Lua is wonderful, it'll be easy to implement that 'specific' behavior with metamethods!". But after a little though and tries out, I realized that this use case was not coverable with __index / __newindex, because those metamethods lacks a 'context'.
>
> Does somebody already encountered/solved that use case ?
Usually the context is the table itself
function __index(t, k)
function __newindex(t, k, v)
where t is the context
Otherwise, just do
myable.optional_value = mytable.optional_value and
mytable.optional_value or "DEFAULT"
This is the typical Lua idiom for setting default values. Be careful
if the value is a boolean though since the and/or ops will work
differently. In that case, you actually have to check the type of the
value.
wes