I don't know what you're calling "different addressing". The reason it enters an infinite loop is because multiple threads cannot execute code in the same Lua state at the same time. So the callback cannot stop the loop because the loop needs to end to allow the callback to execute in the first place.
And even if that wasn't a problem, there's another one: Lua executes synchronously with the rest of the stuff in the server, so even if it wasn't an infinite loop, it would still be blocking the server from updating other things until the response from remote server arrives.
Instead of calling fetchRemote synchronously, you probably want to execute your own Lua code asynchronously, over multiple Lua invocations. You can achieve that using coroutines, which allow the function execution to stop and resume later.
An example:
function fetchRemoteAsync(url, opts)
local co = coroutine.running() -- Store the current coroutine in a variable
local function callback(responseData, errorCode)
-- When the response arrives, resume the coroutine stored in variable co. Also
-- pass responseData and errorCode as values to be returned by coroutine.yield.
coroutine.resume(co, responseData, errorCode)
end
fetchRemote(url, opts, callback)
-- Pause the execution of the current coroutine. It will be
-- resumed when coroutine.resume gets called for this coroutine
-- and any additional arguments will be returned.
local responseData, errorCode = coroutine.yield()
-- The coroutine has resumed, return the data.
return responseData, errorCode
end
function testFetchAndOutput()
local responseData, errorCode = fetchRemoteAsync('http://site.com/foo/bar', { method = 'POST', headers = ... })
outputDebugString(responseData)
end
-- Create a coroutine that will execute testFetchAndOutput
local testCo = coroutine.create(testFetchAndOutput)
-- Execute the coroutine
coroutine.resume(testCo)
As a result, fetchRemoteAsync isn't blocking so you can call it and everything else on the server (including Lua code) can execute before it returns. But it can only be called from a coroutine.