2016-04-08 10 views
2

のエラーを回避することの私は巨大なテーブル、のようなものを持っているとしましょう。それを含むテーブルもありません。私はちょうど行うことができるようにしたいと思います:Lua:ゼロ値のインデックスを作成しようとしました。テーブルが存在することが保証されていない</p> <pre><code>test.test[1].testing.test.test_test </code></pre> <p>:条件文

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

しかし、インデックスのいずれかがまだ定義されていない場合は、もちろん、これは私に「インデックスへの試み(ゼロ値)?」エラーを与えるだろう。何度も、このようなことをするつもりです:

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

これを達成するためのより良い、あまり退屈な方法はありますか?

答えて

2

ルックアップするキーのリストを取得し、エントリが見つかると必要な操作を実行する関数を書くことができます。ここでは例です:

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"}) 

さておき、この種の問題を解決し、関数型プログラミングの概念はMaybe monadです。あなたはおそらくLua implementation of monadsでこれを解決することができますが、それには構文的な砂糖がないのであまりうまくいかないでしょう。

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) 

あなたはまた、空のテーブルを使用します:あなたがnilのため__indexのメタメソッドを設定することで、エラーを上げ避けることができ

+0

非常にきちんとしたソリューションを、ありがとうございました! –

2

debug.setmetatable(nil, { __index={} }) 
関連する問題

 関連する問題