lua-users home
lua-l archive

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


You can write this as:

    local temp = table[index]
    var = temp and temp.field

Or one can write:

    var = (table[index] or {}).field
        -- better if we use a pre-allocated empty table

That being said, I too have wished for a simpler way to do nil-friendly
operations.

http://lua-users.org/lists/lua-l/2004-06/msg00645.html

Mark

on 2/5/05 6:51 AM, Javier Guerra at javier@guerrag.com wrote:

> On Saturday 05 February 2005 9:12 am, Ashwin Hirschi wrote:
>> Of course, having a little error-checking in there wouldn't hurt [unless
>> you're absolutely sure all your data is always available]. For instance, if
>> the 2nd table would somehow be missing, Lua would (quite correctly) throw
>> an alert during your last lua_gettable call. Depending on circumstances,
>> that could be a bit embarrassing, I think.
> 
> that's one thing i think could be different.  in this case, the C calling code
> should do all the error-checking, no argue with that.  but in Lua, i find
> lots of times i want to do something like this:
> 
> var = table[index].field
> 
> but if i'm not sure that [index] is present in that table, i have to split in
> two:
> 
> local temp = table[index]
> if temp then var=temp.field else var=nil end
> 
> usually, i don't care about intermediate values, just if any part of the table
> fetchs fails, the whole expression should be nil, and i'd be happy to check
> the result just once and not every step.
> 
> in short, i'd like that
> (nil)[anything] == nil
> instead of failing
> 
> does anybody object to this?
>