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

Return a string from a program

Started by gigimoi, 02 August 2012 - 05:44 PM
gigimoi #1
Posted 02 August 2012 - 07:44 PM
Is it possible to return a string from a program?

local string s = "Blah"
return s


print(shell.run("returnblah"))
Rsstn #2
Posted 02 August 2012 - 07:50 PM
No, that code would just print 'true'.
Never really thought about that before, but it's a shame that you can't…
ElvishJerricco #3
Posted 05 August 2012 - 08:38 PM
only thing you can really do is use global variables =/
Noodle #4
Posted 06 August 2012 - 11:01 AM
Why do you need a return "string"
??
Rsstn #5
Posted 06 August 2012 - 05:04 PM
You could just run the code as a function, I'm not sure why it's needed as a program.
Noodle #6
Posted 07 August 2012 - 05:10 PM
Example:
function pro()
  if powerLevel > 9000 then
	return true -- True would be the metaphorical "string" in this example. Cannot do any other way (except for nil + false)
  end
end
if pro then
  print("Pro")
end
KFAFSP #7
Posted 07 August 2012 - 06:23 PM
Or you could do the following :


local ProgramPath = <PathHere>
local tEnv = {}
local Success = pcall(os.run, tEnv, ProgramPath)
if Success then
  -- Get the result
  local Result = tEnv.result
end

That requires that the file is a valid lua file, and that it doesnt use

return "stuff"

but :


result = "stuff"

note that you wont be able to execute it normally error-free. You would probably get an "attemptet to write to global" error.
Pharap #8
Posted 08 August 2012 - 05:25 AM
There is one way to get around it.

Make the program you are trying to get the string from to write the string to a file, then have the other program read the string from the file.

So program one:(pseudocode)

Run("program2")
opedfile io.open(fileforreading, readmode)
stringvar = opedfile.readline()
io.close(file)

something close to that at least
KaoS #9
Posted 08 August 2012 - 08:06 AM
load the file as a function using loadfile(path) and then call the function, it should use the return command as normal
KFAFSP #10
Posted 08 August 2012 - 08:16 AM
I think the Environment Access is much faster and also looks coded better. Although writing to a file reminds me of WIndows' STDIN and STDOUT Pipes. A shame that you can't do pipes in lua. There is prob. a way, but that means searching…
KaoS #11
Posted 08 August 2012 - 08:28 AM
What I mean is that instead of using shell.run(programname) use loadfile(programname)()

so if you name it "myprogram" and the file has:

if rs.getInput("back")==true then return "success" end

then simply

print(loadfile("path/myprogram")())

and if you have redsone input at the back it should print "success"
KFAFSP #12
Posted 08 August 2012 - 11:12 AM
Thats the same as dofile! And thats the same as… os.run (almost) ?