How can I load a file of lua tables and variables without polluting the global environment? Since doing a loadfile and running it just loads everything in the global space and may overwrite something else which I don’t want.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Lua 5.1 and without much error handling you could do this:
The first line creates an empty environment table that can see all existing globals, but which cannot trivially change them since they are visible only by proxy through the
__indexmetamethod. Any globals the script creates would be stored inenv, which is returned. This will work well for simple scripts that just set a bunch of configuration parameters, and which might need to call simple safe functions to set them based on conditions at run time.Note that making the globals visible to the script is a convenience. Although the globals cannot be modified from the script in the obvious way,
_Gis a global variable that contains a reference to the global environment (containing_G._G,_G._G._G, etc…) and_Gcan be modified from the script which could lead to further issues.So rather than using
_Gfor the index, it would be much better to construct a table that contains only functions known to be safe and known to be needed by your script’s author.A complete solution would be to run the script in a sandbox, and possibly further protected to prevent accidental (or deliberate) denial of service or worse. Sandboxes are covered in more detail at the Lua User’s Wiki. The topic is deeper than it seems at first glance, but as long as your users are trusted to be non-malicious then practical solutions are straightforward.
Lua 5.2 changes things a little bit by eliminating
setfenv()in favor of a new parameter toload(). Details are also in the wiki page.