Question

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 duplicating the code.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top