Search code examples
asynchronousluagarrys-mod

How to do async functions in Lua?


I have a database query in a function that return the result of this query and in another function I want to retrieve that result but I don't know how to do this async. I'm using "mysqloo" library https://github.com/FredyH/MySQLOO for my database queries.

The first function, with the query :

function meta:getMoney()
    local query2 = databaseObject:query("SELECT economy FROM luvinsastroi_player WHERE steamid = '" .. self:SteamID64() .. "' ")

    query2.onData = function( q, d)
        return tonumber(d['economy'])
    end
    query2:start()
end

then :

hook.Add( "PlayerSay", "MoneyCommand", function( ply, text, team )
    if(text == "/money") then
        local money = ply:getMoney()
        ply:PrintMessage( HUD_PRINTTALK, "Vous avez " .. money .. "€." )
    end
end )

In the second function, money is nil and so Error on ply:PrintMessage ( HUD_PRINTTALK, "Vous avez " .. money .. "€." ) attempt to concatenate a nil value (money)

How to wait return tonumber(d['economy']) from the meta:getMoney() function ?


Solution

  • This might work, but I'm not sure:

    function meta:getMoney(cb)
       local query2 = databaseObject:query("SELECT economy FROM luvinsastroi_player WHERE steamid = '" .. self:SteamID64() .. "' ")
       if cb then 
          query2.onData = function(q, d)
             cb(tonumber(d['economy']))
          end
       else
          query2.onData = function(q, d)
             return tonumber(d['economy'])
          end
       end
       query2:start()
    end
    
    
    hook.Add("PlayerSay", "MoneyCommand", function(ply, text, team)
       if(text == "/money") then
          local function callback_money(money)
             ply:PrintMessage(HUD_PRINTTALK, "Vous avez " .. money .. "€." )
          end
          ply:getMoney(callback_money)
       end
    end)