2016-04-08 5 views
2

hataların önlenmesi en Dev tablo gibi bir şey var diyelim. Bunu içeren tablolar da değil. Sadece yapabilmek istiyorum: endeksleri henüz hiç tanımlı değilse Lua: bir sıfır değerini indekslemeye çalışın; tablo var garanti edilmez</p> <pre><code>test.test[1].testing.test.test_test </code></pre> <p>: Koşullamalar

if test.test[1].testing.test.test_test then 
    print("it exits!") 
end 

Ama tabii

, bu bana "? Indeksi Girişimini (sıfır değeri)" hata verecekti.

if test then 
    if test.test then 
     if test.test[1] then 
     if test.test[1].testing then -- and so on 

Bunu gerçekleştirmek için daha iyi, daha az yorucu yolu var mı: Pek çok kez, böyle bir şey yapıyor bitireceğiz?

cevap

2

Girdiyi bulursa, istediğiniz eylemi aramak ve yapmak için bir anahtar listesi alan bir işlev yazabilirsiniz. Bir kenara, bu tür bir sorun Maybe monad olduğunu çözer fonksiyonel programlama konsepti olarak

function forindices(f, table, indices) 
    local entry = table 

    for _,idx in ipairs(indices) do 
    if type(entry) == 'table' and entry[idx] then 
     entry = entry[idx] 
    else 
     entry = nil 
     break 
    end 
    end 

    if entry then 
    f() 
    end 
end 

test = {test = {{testing = {test = {test_test = 5}}}}} 

-- prints "it exists" 
forindices(function() print("it exists") end, 
      test, 
      {"test", 1, "testing", "test", "test_test"}) 

-- doesn't print 
forindices(function() print("it exists") end, 
      test, 
      {"test", 1, "nope", "test", "test_test"}) 

: İşte bir örnek. Bunu muhtemelen bir Lua implementation of monads ile çözebilirsiniz, bununla birlikte, sözdizimsel bir şeker olmadığı için çok hoş olmazdı.

+0

Çok temiz çözüm, teşekkür ederim! –

2

Sen nil için bir __index metamethod ayarlayarak hataları yükselterek önleyebilirsiniz:

debug.setmetatable(nil, { __index=function() end }) 
print(test.test[1].testing.test.test_test) 
test = {test = {{testing = {test = {test_test = 5}}}}} 
print(test.test[1].testing.test.test_test) 

Ayrıca boş bir tabloyu kullanın:

debug.setmetatable(nil, { __index={} }) 
İlgili konular