当前位置:网站首页>Lua removing elements from a loop in a list

Lua removing elements from a loop in a list

2022-06-11 03:38:00 sayWhat_ sayHello

Preface

stay code I thought of this case :

local t = {
    1, 2, 3, 4, 5}
for i = 1, #t do
	if i == 3 then
		table.remove(t, i)
	end		
end

for i = 1, # t do
	print(t[i])
end

I don't know LUA What is the effect of the program . Because it is not usually supported to delete elements in a loop .
This operation may throw exceptions in other languages . For example, in JAVA This operation is not supported in , Only in the iterator can we correctly delete .

Conclusion

Run the , Found it can run normally :

1
2
4
5

Change the code above :

local t = {
    1, 2, 3, 4, 5}
for i = 1, #t do
	if i == 3 then
		table.remove(t, i)
	end		
    print(t[i])
end

The result is as follows :

1
2
4
5
nil

It can be found that when the coordinates are 3 The element of has been removed , Subsequent elements move forward .

A clever way

As mentioned above, such deletion will cause the following elements to move forward , But this traversal is followed by nil, Does not conform to the logic of the program .
A trick is to turn it upside down :

local t = {
    1, 2, 3, 4, 5}
for i = #t, 1, -1 do
	if i == 3 then
		table.remove(t, i)
	end		
    print(t[i])
end

Output :

5
4
4
2
1

You can press here to output two 4, Because 3 Deleted , Put it in 3 The position is now 4.
In business logic This situation is equivalent to determining whether to delete more than once . Correct scheme .
If you have done other operations besides judging whether to delete, you should be careful with this method .

原网站

版权声明
本文为[sayWhat_ sayHello]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020554154930.html