Allow loadfile() when require() would be allowed
Posted: Fri May 09, 2025 1:12 pm
I'd like the Lua function loadfile to work, with the same restrictions as require and load (starting at mod root, not in event handlers, etc., only in text mode, only with .lua extension, etc.). I would be OK with an extra restriction that prevents loadfile from loading files in other mods, if you're concerned, but really the basic cross-mod require can already do a lot of stuff, so I'm not sure this is much worse.
For our own files, this is equivalent to changing the target .lua module to return a large string of all the Lua code, then calling require and passing that to load, so it doesn't let us do anything new, but I really don't want to write the code in a large multi-line string.
Why:
I have a test framework in my mod for running tests. I can run tests both outside Factorio, in normal lua5.2, and inside Factorio. It's nice to be able to run the tests in the real runtime. But some of my tests need to control Factorio globals, such as "game" or "script", and I do so by using loadfile with a custom environment. I could try to mess with _G but that's a lot riskier, and not really a good Lua practice, at least in 5.2. Those tests currently can't run inside Factorio and I'd like to fix that.
Thank you for your consideration
For our own files, this is equivalent to changing the target .lua module to return a large string of all the Lua code, then calling require and passing that to load, so it doesn't let us do anything new, but I really don't want to write the code in a large multi-line string.
Why:
I have a test framework in my mod for running tests. I can run tests both outside Factorio, in normal lua5.2, and inside Factorio. It's nice to be able to run the tests in the real runtime. But some of my tests need to control Factorio globals, such as "game" or "script", and I do so by using loadfile with a custom environment. I could try to mess with _G but that's a lot riskier, and not really a good Lua practice, at least in 5.2. Those tests currently can't run inside Factorio and I'd like to fix that.
Thank you for your consideration
