1619 posts
Posted 04 May 2013 - 03:38 PM
I've heard that function environments could be used to "sandbox" a program. I decided to write an OS, and wanted to know how I could use these function environments to sandbox user-created programs. I also want to know how to switch back to _G when the system needs to do something. Thanks!
1522 posts
Location
The Netherlands
Posted 04 May 2013 - 04:08 PM
The first what would come up to me is the following.
First you 'back-up' your function or table, and then you make your new function or table. Just like the following:
local example = {
x = function()
write("Hello!")
end,
y = function()
write("bye!")
end
}
local nativeExample = example -- back up
example = {
x = function()
write("Bye!")
end,
y = function()
write("hello!")
end
}
example.x() -- Bye!
nativeExample.x() -- Hello!
You would do pretty much the same for functions. Im also sure this is not the full explanation, so just wait for those who know this better then me :P/>
1619 posts
Posted 04 May 2013 - 04:09 PM
The first what would come up to me is the following.
First you 'back-up' your function or table, and then you make your new function. Just like the following:
local example = {
x = function()
write("Hello!")
end,
y = function()
write("bye!")
end
}
local nativeExample = example -- back up
example = {
x = function()
write("Bye!")
end,
y = function()
write("hello!")
end
}
example.x() -- Bye!
nativeExample.x() -- Hello!
You would do pretty much the same for functions. Im also sure this is not the full explanation, so just wait for those who know this better then me :P/>
That's not a function environment. I'm talking about setfenv() and stuff like that.
1522 posts
Location
The Netherlands
Posted 04 May 2013 - 04:14 PM
Okay derp on me :P/>
I would refer you to this:
http://www.lua.org/pil/14.3.html
379 posts
Location
Hawaii
Posted 05 May 2013 - 01:38 AM
When you set the environment of a function, you set whats in its global scope. This way, you can override certain functions that another function can access. So if you change term.setCursorPos() in the environment of one function, it won't affect term.setCursorPos() in another function (unless you set the environment of a higher level function).