This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Dlcruz129's profile picture

Function Environments

Started by Dlcruz129, 04 May 2013 - 01:38 PM
Dlcruz129 #1
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!
Engineer #2
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/>
Dlcruz129 #3
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.
Engineer #4
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
Smiley43210 #5
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).