lua-users home
lua-l archive

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


Am 18.05.2014 06:16 schröbte Andrew Starks:
On Sat, May 17, 2014 at 1:50 PM, Andrew Starks <andrew.starks@trms.com>wrote:

On Saturday, May 17, 2014, Roberto Ierusalimschy <roberto@inf.puc-rio.br>
wrote:

I want something like |local v = t?t1?t2?t3|... (actually I want
|local v = t?.t1?.t2?.t3|...)

Another option:

    local v = (((t or E).t1 or E).t2 or E).t3

(where E={} is defined somewhere in your code...)


local a = {b ={c = {d = nil}}}
print(((a.b.c.d or empty).e.f or empty).g )
```

I don't like it as much. Maybe someone has some ideas. Most often I'm
  checking to see if something exists or if it does it could be a table.
With this, I'd have to say:

```
local ((a.b.c.d or empty).e.f or empty).g  = test_val
if  not (test_val == nil or test_val == empty) then

end



What about:

    local E = require( "empty" )
    local a, x = { b = { c = { d = { e = "ok" } } } }, nil
    print( (((a or E[4]).b or E[3]).c.d or E[1]).e ) --> ok
    print( (((x or E[4]).b or E[3]).c.d or E[1]).e ) --> nil
    print( (((a or E[4]).x or E[3]).c.d or E[1]).e ) --> nil
    print( (((a or E[4]).b or E[3]).c.x or E[1]).e ) --> nil
    print( (((a or E[4]).b or E[3]).c.d or E[1]).x ) --> nil



I'm not sure that that is all that much pretty or clearer than:

-- check for g, but first check if d as there and it has a valid f.
if a.b.c.d and a.b.c.d.e.f and a.b.c.d.e.f.g then

I'd much prefer:

if a.b.c?d.e?f.g then -- (or the .?)


but that's just me.But it's not a giant pain, either.

What kind of data structures are you guys dealing with? The longest sequence of fixed length with constant table lookups in my code is `package.loaded.math`, and even for non-constant table lookups (the hypothetical `?[var]` syntax) I have found only one place where I could use this (the length is fixed there because I generate code at runtime for a particular case) ...


-Andrew


Philipp

local assert = assert
local error = assert( error )
local type = assert( type )
local setmetatable = assert( setmetatable )


local function readonly()
  error( "this table is readonly", 2 )
end

local M = { (setmetatable( {}, { __newindex = readonly } )) }
local M_meta = {}

function M_meta:__index( i )
  if type( i ) == "number" and i >= 1 and i % 1 == 0 then
    local t, meta = {}, { __newindex = readonly }
    function meta:__index( k )
      return M[ i-1 ]
    end
    setmetatable( t, meta )
    M[ i ] = t
    return t
  end
end

return setmetatable( M, M_meta )