Lua:如何根据条件执行不同的块?
我有这个表:
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"},
}
这个函数:
function testfoo()
i = 1
while no_table[i] ~= nil do
foo(no_table[i])
i = i + 1
end
end
和 foo 函数:
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
你能帮我找到吗? :
一种能够检查两个表是否相等的方法(目前它让我无法索引为零)
如果等式为真,则仅执行“print (b+c)”代码,或者如果不为真,则先执行“print (a+b)”,然后执行“print ( b+c) 其次不重复代码。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在这方面看到了很多问题。首先,我永远不会依赖在外部函数中设置的
i
,它实际上应该是一个局部变量,并在需要时作为参数传递。也就是说,在尝试访问no_table[x][y]
之前,您需要检查no_table[x]
是否存在。因此,对于foo
,您需要:另外,对于表中的数字,如果您想要进行算术运算,则需要删除引号:
接下来,在
testfoo
中,你正在传递一个表,所以你要么需要在函数调用中拆分 a、b、c 和 d 的值,要么你可以只传递表本身并在 foo: 中处理它:这会导致:
编辑:最后一次清理,由于条件相同,您可以使用
else
而不是elseif
: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 ifno_table[x]
exists before trying to accessno_table[x][y]
. So, forfoo
you'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
else
rather than anelseif
: