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? :
-
A way to be able to check if the two tables are or not equal (currently it gives me cannot index nil)
-
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.
Lots of problems I’m seeing in this. First, I’d never rely on
ibeing 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 ifno_table[x]exists before trying to accessno_table[x][y]. So, forfooyou’d have:Also, for numbers in the table, if you want to do arithmetic, you need to remove the quotes:
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:This results in:
Edit: One final cleanup, since the conditions are the same, you can use an
elserather than anelseif: