Function Lua:如何根据条件执行不同的块?
我有这张桌子:Function Lua:如何根据条件执行不同的块?,function,printing,lua,null,lua-table,Function,Printing,Lua,Null,Lua 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"}, } 此功能: function testfoo() i = 1 while no_table[i] ~= nil do foo(no_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"},
}
此功能:
function testfoo()
i = 1
while no_table[i] ~= nil do
foo(no_table[i])
i = i + 1
end
end
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
以及foo函数:
function testfoo()
i = 1
while no_table[i] ~= nil do
foo(no_table[i])
i = i + 1
end
end
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
你能帮我找到吗
我在这里看到了很多问题。首先,我从不依赖于在外部函数中设置
I
,如果需要,它实际上应该是一个局部变量并作为参数传递。也就是说,在尝试访问无表[x][y]之前,需要检查无表[x]
是否存在
。因此,对于foo
,您需要:
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
此外,对于表中的数字,如果要进行算术运算,则需要删除引号:
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"},
}
接下来,在testfoo
中,您将传递一个表,因此您需要在函数调用中拆分a、b、c和d的值,或者您只需传递表本身并在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
这导致:
> testfoo()
25
37
31
编辑:最后一次清理,由于条件相同,您可以使用else
而不是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
在no_table中,根据当前函数:
no_table[i]={a=3,b=22,c=18,d=“ABC”}
no_table[i-1]--不存在
,no_table[i][4]=ABC
no_table[i-1][4]--也不存在@observ:不理解您的问题。如果没有表格[x]如果无表中的条目不存在,则将返回false。基本上,我的问题是当我尝试执行无表[i][4]~=无表[i-1][4]
时,因为第一次运行脚本时i-1不存在,因此它将尝试将某个值与nil进行比较。我已尝试为i>=2执行无表[i][4]~=no_table[i-1][4]然后
但它不起作用。你有一个逻辑错误,而不是Lua错误。使用你提供的代码,它在中工作,如果no_table[i]和no_table[i-1],然后…否则…结束
代码。不要尝试比较no_table[i][4]~=no_table[i-1][4]
先确认父表是否存在。这很有效。非常感谢您提供的解决方案和建议。