I am having an issue with something I am trying to make, I am setting a variable equal to a function of mine, I am having trouble pulling the data OUT of the callback function. It reads fine inside the callback, but I can't seem to find a way to get the data out of the callback function.
[CODE]function APP_SYS.LoadData()
local values
queryStr = "The query I am using to pull the data"
query(queryStr, function( data )
values = data
end)
return values
end[/CODE]
query is just a local function I found in another MySQL based addon that I saw as useful and clean.
I left out the query string just because it is not needed for this question, the query I use IS working.
[CODE]local function query( str, callback )
local q = db:query( str )
function q:onSuccess( data )
callback( data )
end
function q:onError( err )
if db:status() == mysqloo.DATABASE_NOT_CONNECTED then
table.insert( queue, { str, callback } )
db:connect()
return end
end
q:start()
end[/CODE]
After testing multiple things I have personally determined it is not possible without either using external functions or a local table to hold the data, then return that table[key].
What you need to understand about your query function is that it is non-blocking and is not returned instantly. Now the first part, non-blocking, means the game isn't going to stop everything its doing to wait for query function to return information from the database. If it did that then the game would effectively freeze each time the game queried the database. So instead the game continues on with what it needs to do while it waits for the database to return the queried data. When that happens your callback function gets called, but by then the LoadData function has already been completed and your values variable no longer exists.
tl;dr - You need to make values a global variable if you want to assign values to it in a callback. Also, because its a callback, you won't ever get the information instantly. So you'll have to take into account the, albeit brief, time delay.
EDIT: Global variables, got it =) Thanks for the help.
Sorry, you need to Log In to post a reply to this thread.