如何在Lua中进行异步函数?

我有一个数据库查询函数,它返回此查询的结果,我想在另一个函数中检索该结果,但我不知道如何进行异步。 我正在使用 “mysqloo” 库 https://github.com/FredyH/MySQLOO 进行数据库查询。

第一个查询函数如下:

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

然后:

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

在第二个函数中,money 是空值,因此“Error on ply:PrintMessage (HUD_PRINTTALK, "You have " .. money .. "€." ) attempt to concatenate a nil value (money)”。

如何等待从 meta:getMoney() 函数返回的 return tonumber(d['economy'])

点赞
用户1847592
用户1847592

这个可能会起作用,但我不确定:

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)
2019-10-06 14:49:32