See the discussion in the Lua User Wiki sandbox , and the more general topic of script security . There are a number of subtle and not so subtle problems with these kinds of things. This can be done, but protection from code such as for i=1,1e39 do end requires more than just limiting which features are available for the sandbox.
The general methodology is to create a functional environment for the sandbox, in which there is a white list of allowed functions. In some cases, this list may even be empty, but, for example, the user can have access to pairs() , for example, is practically harmless. On the sandbox page there is a list of system functions, broken by their security, as a convenient link to build such a white list.
Then you use lua_setfenv() to apply the function environment to the user script that you loaded (but have not yet executed) with lua_loadfile() or lua_loadstring() , if necessary. With a connected environment, you can execute it using lua_pcall() and friends. Before executing, some people actually scanned the downloaded bytecode for operations that they did not want to allow. This can be used to completely inhibit loops or write global variables.
Another note is that load functions usually load either precompiled bytecode or Lua text. It turns out that it is much safer if you never allow a pre-compiled bytecode, since several ways have been revealed to make the virtual machine behave erroneously, which all depends on manual work with invalid bytecode. Since bytecode files start with a well-defined byte sequence, which is not plain ASCII text, all you have to do is read the script into a string buffer, check for the absence of a marker and pass it only to lua_loadstring() if it is not bytecode .
For many years, this kind of discussion was held in the Lua-L mailing list section, so searching there is also likely to be useful.
RBerteig
source share