Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove key value from the table in loop in Lua

So, I created a table A_table and my goal is to create a set of three hands Hand and then I wanted to remove the last two sets from the table i.e key 2 and 3

A_table = {}

for i = 1, 3 do
  local  Hand = {
            ['parts'] = {
                type = 'arm',
                left = 'up',
                right = 'down',
                collision = 'true'
            }
        }
    
    table.insert(A_table, Hand)
end

for k, v in pairs(A_table) do
    print(k, v['parts'].left)
end

Output: — Wanted to remove 2 and 3

1       up
2       up
3       up

I tried the following method but it didn’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for k, v in pairs(A_table) do
    for i = #v, 2, -1 do
        A_table[i] = nil
    end
end 

>Solution :

In your case…

for i = #A_table, 2, -1 do
    table.remove(A_table)
end
  1. The loop starts at last key and leaves after key number 2
  2. table.remove() without positional parameter removes last key/value by default
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading