So I've become annoyed at the global by default style in Lua. I'm trying to write a program which will make all programs that run after it incapable of creating global variables. When they try to, that variable will be set to the function environment of that program. I've come up with this, and it seems to work, but for some reason is throwing an error in [edit: 9] in the ComputerCraft rom/programs/edit. When I run a test program,
a = 1
print(a)
it works fine and prevents the global variable from being created while still allowing it to be accessed by that program, but it doesn't work for other programs. I've tried doing _G.a, local a, and other things, but all of them work. Does anyone have any ideas why it might not work on other programs?
local oldload = loadfile
function _G.loadfile(str)
local func = oldload(str)
local env = {}
env._G = env
setmetatable(env, {__index = _G, __newindex =
function(table, var, val)
rawset(env, var, val)
end})
setfenv(func, env)
return func
end