This is a read-only snapshot of the ComputerCraft forums,
taken in April 2020.
Need to run code inside program.
Started by nutcase84, 31 March 2013 - 08:43 AMPosted 31 March 2013 - 10:43 AM
Can't figure out how. Like runCode(code).
Posted 31 March 2013 - 11:16 AM
pcall(setfenv(loadstring(text),getfenv(1))
Posted 31 March 2013 - 11:22 AM
pcall(setfenv(loadstring(text),getfenv(1))
Thank you!
But I had to add another ) to the end.
Posted 31 March 2013 - 11:28 AM
Lol, that's what I thought when I posted it. XD
Posted 31 March 2013 - 11:43 AM
Or just, for simplicity, loadstring("print('lol')")()
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:
It's longer, but it's easier for me to read, understand, and build upon, and isn't as syntactically cluttered.
-- 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.
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.
Posted 31 March 2013 - 11:49 AM
IIRC, functions made with loadstring are supplied with all of the default functions/variables, just not those defined in the script.Or just, for simplicity, loadstring("print('lol')")()
It would error with attempt to call nil, you have not supplied it an environment.
I think.
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.Posted 31 March 2013 - 11:50 AM
That makes sense now. :wacko:/>