Safely remove items from an array table while iterating

the general case of iterating over an array and removing random items from the middle while continuing to iterate If you’re iterating front-to-back, when you remove element N, the next element in your iteration (N+1) gets shifted down into that position. If you increment your iteration variable (as ipairs does), you’ll skip that element. There … Read more

How to get number of entries in a Lua table?

You already have the solution in the question — the only way is to iterate the whole table with pairs(..). function tablelength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end Also, notice that the “#” operator’s definition is a bit more complicated than that. Let … Read more

How do you copy a Lua table by value?

Table copy has many potential definitions. It depends on whether you want simple or deep copy, whether you want to copy, share or ignore metatables, etc. There is no single implementation that could satisfy everybody. One approach is to simply create a new table and duplicate all key/value pairs: function table.shallow_copy(t) local t2 = {} … Read more

How can I create a secure Lua sandbox?

You can set the function environment that you run the untrusted code in via setfenv(). Here’s an outline: local env = {ipairs} setfenv(user_script, env) pcall(user_script) The user_script function can only access what is in its environment. So you can then explicitly add in the functions that you want the untrusted code to have access to … Read more