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

Having trouble using returned value from function in loaded API

Started by Jtpetch, 21 September 2016 - 07:50 PM
Jtpetch #1
Posted 21 September 2016 - 09:50 PM
So I'm working on a sort of "question-answer" program, and I'm having trouble returning variables from a loaded API ("dictionary")

This is the code that's not working in the main program:

os.loadAPI("AI_dictionary") --[[This loads my dictionary file]]
local input
input=tostring(read())
x=AI_dictionary.handlers(input) --[[This (should) set x equal to the variable returned by my dictionary API]]
print(x) --[[This should just print the variable returned]]
end

And this is the dictionary file:

--[[This handles the input from the main program]]
function handlers(userInput)
response=default
if userInput:lower():find("hello") or userInput:lower():find("hi") then
  hello()
end
end
--[[This is the response randomizer]]
function random(y)
local rand=math.random(1,y)
return rand
end
--[[This is the "definition" for hello and it's variants]]
function hello()
local r=random(3)
if r==1 then response="Hi there!" end
if r==2 then response="Hiya!" end
if r==3 then response="Hi "..userName.."!" end --[[This response uses the user's inputted name (which works, and has nothing to do with the problem)]]
return response
end

Now, I'm not sure if I'm just not using "return" right, or if there's something else completely wrong, but I'm sorta at a loss as to why it's not working.
When running the program, it just prints nil.
Edited on 21 September 2016 - 07:51 PM
KingofGamesYami #2
Posted 21 September 2016 - 10:03 PM
The "handlers" function does not return a value. It also does not save the value returned by your "hello" function.

Assuming you wish to return the value returned by the hello function, you should do this:

return hello()
Lupus590 #3
Posted 21 September 2016 - 10:19 PM
run your API via the lua prompt

test each function separately and see if they return what you expect

run your API via the lua prompt

test each function separately and see if they return what you expect
Jtpetch #4
Posted 22 September 2016 - 01:35 AM
The "handlers" function does not return a value. It also does not save the value returned by your "hello" function.

Assuming you wish to return the value returned by the hello function, you should do this:

return hello()

Yep, that did it!
Realistically, this was a logic problem on my part; Should have realized that I'm not actually directly calling the hello() function, but rather calling the handlers() function first, which then calls the hello() function.
Thank you!