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

Need to run code inside program.

Started by nutcase84, 31 March 2013 - 08:43 AM
nutcase84 #1
Posted 31 March 2013 - 10:43 AM
Can't figure out how. Like runCode(code).
MudkipTheEpic #2
Posted 31 March 2013 - 11:16 AM
pcall(setfenv(loadstring(text),getfenv(1))
nutcase84 #3
Posted 31 March 2013 - 11:22 AM
pcall(setfenv(loadstring(text),getfenv(1))

Thank you!

But I had to add another ) to the end.
MudkipTheEpic #4
Posted 31 March 2013 - 11:28 AM
Lol, that's what I thought when I posted it. XD
Mads #5
Posted 31 March 2013 - 11:43 AM
Or just, for simplicity, loadstring("print('lol')")()
Kingdaro #6
Posted 31 March 2013 - 11:46 AM
Eh, it works but it's a little "dirty" for my tastes. I'd rather do something like:


-- sets only "ok" to false, while other variables are nil
local ok, func, err = false

-- if there was a syntax error, it will be in err
func, err = loadstring("your=code(here)")

-- if there is a syntax error, it will skip this and keep it in err, and ok will be false
-- if there is no syntax error,
if func then
  -- try for a coding error, and change err to the coding err
  -- if there is no coding error, ok will be true
  setfenv(func, getfenv(0))
  ok, err = pcall(func)
end

-- so in the end, ok will be true if successful, and false if not successful for whatever reason.
if not ok then
  print(err)
end

It's longer, but it's easier for me to read, understand, and build upon, and isn't as syntactically cluttered.
MudkipTheEpic #7
Posted 31 March 2013 - 11:46 AM
Or just, for simplicity, loadstring("print('lol')")()

It would error with attempt to call nil, you have not supplied it an environment.

I think.
Kingdaro #8
Posted 31 March 2013 - 11:49 AM
Or just, for simplicity, loadstring("print('lol')")()

It would error with attempt to call nil, you have not supplied it an environment.

I think.
IIRC, functions made with loadstring are supplied with all of the default functions/variables, just not those defined in the script.

EDIT: Just tried it,

> bacon = 5
> loadstring "print(bacon)" ()
5
I'm not sure if this applies in CC though; I did this in my terminal.
MudkipTheEpic #9
Posted 31 March 2013 - 11:50 AM
That makes sense now. :wacko:/>