So, I'm trying to get a variable out of a function. I have a Garry's Mod script which contains this statement:
http.Fetch("http://google.fr", function(body)
return body
end)
My question is: how to retrieve my body variable out of this? I think that there's no such thing as "global" keyword (like in PHP for example) or references in Lua. Thanks!
the easiest way for you to handle this would be to write a function that physically loads the body
result to whatever interface you are using, or to add code inside the Fetch call to load it yourself. Something like this:
-- just an example of some function that knew how to load a body result
-- in your context
function setBody(body)
someapi.Display(body)
end
http.Fetch('http://someurl.com',
function(body)
-- you have access to outer functions from this scope. if you have
-- some function or method for loading the response, invoke it here
setBody(body)
-- or just someapi.Display(body)
end
)
I think you are confused because you seem to be in more of a functional design mindset, and you're now mixing in event driven design. in the event driven design, you are basically calling functions with params and giving them a function callback that has some code that you want to eventually run once the function you invoked completes.
Also, there is a global keyword of sorts in Lua - you have the global table _G
. You could potentially set _G.body = body
, but I would avoid that and pass around callback functions that know how to load things once they are invoked.