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

Running string code inside program

Started by Drifter, 05 April 2013 - 01:09 AM
Drifter #1
Posted 05 April 2013 - 03:09 AM
I want to run code inside a program. I found solution for this:

someCode = "print("Yay!")
pcall(setfenv(loadstring(someCode),getfenv(1)))

but, I have 2 files. First is a startup file, which is running whole time, second is an api, where are functions.
And now, I want to run code from this api file, but with enviroment of startup.

Example:

startup file:


function someFunction(argument)
if argument>0 then
  print("Yay!")
else
  print("Nah!")
end
end

os.loadAPI("myapi")
someCode = "someFunction(5)"
myapi.runThis(someCode)

myapi file:


function runThis(code)
  pcall(setfenv(loadstring(code),getfenv(1)))
end

Problem is, this way,i can run functions inside myapi, byt not inside startup program. I know something is wrong with enviroment,
but I don't have enough experience with this. Basicly, I want to be able to run functions inside startup file like in this example.
Obviously I have much more difficult code, but I am stuck on this problem.

Thnx for help.
Mads #2
Posted 05 April 2013 - 04:17 AM
Try this:

Code in API:

function runThis(code, env)
	pcall(setfenv(loadstring(code), env))
end

When calling:

api.runThis(someCode, getfenv(1))

You are now passing in the environment from the startup file, and therefore the API can use variables and functions and whatnot from there.
Drifter #3
Posted 05 April 2013 - 05:13 AM
And when I have multiple functions in api, I must pass enviroment to every function. Is there any way to pass it once for all functions in api?
Kingdaro #4
Posted 05 April 2013 - 05:28 AM
You could just have a specific function for setting the environment, then keep it as a local variable in your API.

In startup:

os.loadAPI('myapi')
myapi.setEnv(getfenv(1))
myapi.runCode('some(wonderful, code)')

In myapi:

local env

function setEnv(_env)
  env = _env
end

function runCode(code)
  pcall(setfenv(loadstring(code),env))
end
Drifter #5
Posted 05 April 2013 - 06:12 AM
Thnx, this is what I want!
JokerRH #6
Posted 05 April 2013 - 06:54 AM
Or you can get the enviroment of the api that was called bofore yours.
So if Startup runs and then myAPI you can get the enviroment by using getfenv(2), since getfenv will return the enviroment at the given stacklevel.
Drifter #7
Posted 05 April 2013 - 07:21 AM
getfenv(2) isn't working for me
JokerRH #8
Posted 05 April 2013 - 09:20 AM
It definetly works, nearly all my programs are based on that…You just have to find the right stacklevel…:D/>
Drifter #9
Posted 05 April 2013 - 09:37 AM
Oh yea, it works. I am derp :(/> ,made a mistake. Thnx this is I think the best solution.