[SOLVED] Function only returns nil

Started by thselukas, Dec 22, 2020, 07:25 PM

Previous topic - Next topic

thselukas

To explain my problem, I want to make a simple program where I can type a command for example in a wireless pocket computer and a turtle will execute the command.

Code for the turtle:

rednet.open("left")
 
while true do
local _, command = rednet.receive()
exec = loadstring(command)
print(command)
if exec ~= nil
then
value = exec()
rednet.send(0, value) --This returns nill
--print(returnValue) For debugging

else
rednet.send(0, "ERROR")
end

--rednet.broadcast( returnValue)  My attemps to fix the problem
--print(returnValue)
sleep(0.1)
end

This is the code for the advanced computer with a modem:
rednet.open("front")

while true do
command = read()
rednet.send(1, command)
_,returnv = rednet.receive()
print(returnv) --should return the value of the action e. g. true
end

Now, when I give the turtle a command, for example turtle.forward(), the command is executed and the turtle moves forward, but my return value is nil. I tested a bit and I guess it is that way, because of the way I execute my commands (with loadstring(command)). Is there any way, that the return value isn't nil?

thanks in advance

Lupus590

In your turtle code you print returnValue which is never initialised and so will always be nil.

thselukas

I'm sorry, I worded the question wrong and commented the wrong line of code. I meant the 10th line in the turtle code (rednet.send(0, value)). Because if I do " value = turtle.forward() " and then send value via rednet to an other computer, I get true or false. But if I do " exec = loadstring("turtle.forward()") " and then " value = exec() " and then send value via rednet I get nil. I am assuming it is because of loadstring() but I'm not sure. The returnValue was there to see, if tostring() would do anything and maybe fix it (it didn't work).

Lupus590

Change your loaded string to "return "..command and it will then return what the command would return.

This is because loadstring wraps your code into a function to execute it.
local exec = loadstring("turtle.forward()")
-- is equivalent to

local function exec()
  turtle.forward()
end

-- with the return in there we get
local exec = loadstring("return turtle.forward()")
-- is equivalent to

local function exec()
  return turtle.forward()
end

thselukas

Thanks for the quick response. It works now.