如何在 Lua 中执行异步功能?
How to do async functions in Lua?
我在一个函数中有一个数据库查询 return 此查询的结果,在另一个函数中我想检索该结果,但我不知道如何执行此异步操作。
我正在使用 "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, "Vous avez " .. money .. "€." )
end
end )
在第二个函数中,money 为 nil,所以 Error on ply:PrintMessage ( HUD_PRINTTALK, "Vous avez " .. money .. "€." ) attempt to concatenate a nil value (money)
如何从 meta:getMoney()
函数等待 return tonumber(d['economy'])
?
这可能有效,但我不确定:
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)
我在一个函数中有一个数据库查询 return 此查询的结果,在另一个函数中我想检索该结果,但我不知道如何执行此异步操作。 我正在使用 "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, "Vous avez " .. money .. "€." )
end
end )
在第二个函数中,money 为 nil,所以 Error on ply:PrintMessage ( HUD_PRINTTALK, "Vous avez " .. money .. "€." ) attempt to concatenate a nil value (money)
如何从 meta:getMoney()
函数等待 return tonumber(d['economy'])
?
这可能有效,但我不确定:
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)