How to a) duplicate a Lua table? And b) clear a table to start fresh?

What's the best way to make a duplicate of a (small) table with integer keys?

I have populated a table levels which always contains exactly 7 images. Internal order is irrelevant (I never iterate them) but I do math to pick a level--so the integer keys are helpful.

Then I have a second table backups for storing up to 9 DUPLICATES of (not references to) the entire levels table. (Those keys could be integers or strings: 4, 8, 9 or "B4", "B8", "B9".) So: tables nested in a table.

How would I duplicate levels into an item within backups, and then retrieve it into levels later?

And how would I clear a table? (To start fresh with 0 items and re-populate it.) (Online examples have failed me: they are multi-line processes that don't seem to work with tables passed into a function--so I'd have to hard-code them every time.)

FWIW, I first tried shallowcopy but it crashes with some C error about "table expected" if I try to copy from a table that is INSIDE another table--like this:

levels = table.shallowcopy(backups["B1"])

Thanks in advance!

Some alternative approaches to Copy at

http://lua-users.org/wiki/CopyTable

For Remove/Clear on a table passed into a function then are you working on a copy not the original? Hmm. Interesting.

1 Like

I'm not yet prepared to say that's the issue with certainty! But something is amiss... I'll keep exploring. Thanks for the link!