开发者

Lua: How to execute different blocks depending on conditions?

I have this table:

no_table ={
        {a="3", b="22", c="18", d="ABC"},
        {a="4", b="12", c="25", d="ABC"},
        {a="5", b="15", c="16", d="CDE"},
               }

This function:

function testfoo()
    i = 1
    while no_table[i] ~= nil do
        foo(no_table[i])
        i = i + 1
    end
end

and the foo function:

function foo(a,b,c,d)
    if no_table[i][4] ~= no_table[i-1][4]
        then
           print (a+b)
    elseif no_table[i][4] == no_table[i-1][4]
        then
           print (b+c)
    end
end

Can you help me find? :

  1. A way to be able to check if the two tables are or not equal (currently it gives me cannot index nil)

  2. A way to execute only the "print (b+c)" code if the equality is true, or if is not true then both "print (a+b)" first and "print (b+c) secondly without duplic开发者_JAVA百科ating the code.


Lots of problems I'm seeing in this. First, I'd never rely on i being set in an external function, it really should be a local variable and passed as a parameter if you need it. That said, you need to check if no_table[x] exists before trying to access no_table[x][y]. So, for foo you'd have:

function foo(a,b,c,d)
    if not (no_table[i] and no_table[i-1] and no_table[i][4] == no_table[i-1][4])
        then
           print (a+b)
    elseif no_table[i] and no_table[i-1] and no_table[i][4] == no_table[i-1][4]
        then
           print (b+c)
    end
end

Also, for numbers in the table, if you want to do arithmetic, you need to remove the quotes:

no_table ={
        {a=3, b=22, c=18, d="ABC"},
        {a=4, b=12, c=25, d="ABC"},
        {a=5, b=15, c=16, d="CDE"},
               }

Next, in testfoo, you're passing a table, so you either need to split out the values of a, b, c, and d on your function call, or you can just pass the table itself and handle that in foo:

function foo(t)
    if not (no_table[i] and no_table[i-1] and no_table[i][4] == no_table[i-1][4])
        then
           print (t.a+t.b)
    elseif no_table[i] and no_table[i-1] and no_table[i][4] == no_table[i-1][4]
        then
           print (t.b+t.c)
    end
end

This results in:

> testfoo()
25
37
31

Edit: One final cleanup, since the conditions are the same, you can use an else rather than an elseif:

function foo(t)
    if no_table[i] and no_table[i-1] and no_table[i][4] == no_table[i-1][4]
        then
           print (t.b+t.c)
    else
           print (t.a+t.b)
    end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜