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

send a script through rednet to be executed on the other side

Started by Varscott11, 03 July 2016 - 04:11 PM
Varscott11 #1
Posted 03 July 2016 - 06:11 PM
I have a system that needs to send a whole script file through rednet, that gets executed on the other computer. If this is even possible, does anyone know a way to do it? I've searched everywhere with no avail. Any help is appreciated!
LBPHacker #2
Posted 03 July 2016 - 06:37 PM
Well, you can send strings over rednet, and programs are stored in files which you can load into strings. Therefore you can send programs, eh?

Here's your todo list:
  • open a file (hint)
  • read its contents into a string
  • send the string over rednet (hint)
Edited on 03 July 2016 - 04:38 PM
Varscott11 #3
Posted 03 July 2016 - 07:54 PM
Is there a way to execute that string like its own program?
LBPHacker #4
Posted 03 July 2016 - 08:16 PM
Oh, okay, you got stuck on the receiving side of things. Sure, there is a way. When a program is loaded from a file, the content of the file is passed to the standard Lua function load (or loadstring, depending on which version of Lua is used). load returns a function, which then can be called and thus the program can be run.

The second argument to both load and loadstring is the so called chunkname. This is what you see in an error message before the line number.

local program_string = ... -- receive the string through rednet, whatever

local program_function, load_error = load(program_string, "came-through-rednet") -- you could also send the chunkname over rednet

-- beware, program_function might be nil, which means that program_string wasn't a valid Lua source;
-- in that case load_error will hold the error message
program_function()

You could even send the arguments to the program over rednet. You'd have to pass them to program_function.
Edited on 03 July 2016 - 06:18 PM
Varscott11 #5
Posted 03 July 2016 - 08:44 PM
Very nice. Thank you for your support. I was clueless before!