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

pcall return value

Started by Nothy, 23 March 2017 - 11:49 AM
Nothy #1
Posted 23 March 2017 - 12:49 PM
Basically, what I'm trying to do is load a piece of code that returns the value "hello".
But, I can't get it to display said returned value when using pcall.
Any ideas as to why?

  local code = io.read()
  local f = loadstring(code)
  local ok, err = pcall(f)
  if err then
	write("Program error: "..err.."\n")
  else
	term.setTextColor(colors.yellow)
	print(ok,err)
	term.setTextColor(colors.white)
  end
EDIT: Here's what it spits out:
Edited on 23 March 2017 - 11:54 AM
SquidDev #2
Posted 23 March 2017 - 02:19 PM
The issue is that you're not returning a value in either case. Let's "expand" the code to see what is actually executed:


local ok, result = pcall(function()
    function a() return "hi" end
end)
Here you just create a function and do nothing with it.

local ok, result = pcall(function()
    a()
end)
And here you called the function, but didn't return it or anything.

Instead, you'd have to use return a(). However, if you're going for a REPL, that's less than ideal. Instead, you should attempt to load the string with "return " prepended, before loading the original string. This is how the built-in Lua program does it.
Nothy #3
Posted 23 March 2017 - 03:25 PM
Right, I'll have a go at that.