在你的代码中,有几个问题可能导致`/settitle`命令无法正常工作。以下是修复后的代码并附上相关注释:
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
local playerTitles = {} -- 缓存玩家头衔
-- 获取玩家头衔的回调
ESX.RegisterServerCallback('custom_title:getPlayerTitle', function(source, cb, targetServerId)
local xPlayer = ESX.GetPlayerFromId(targetServerId)
if xPlayer then
MySQL.Async.fetchScalar('SELECT title FROM users WHERE identifier = @identifier', {
['@identifier'] = xPlayer.identifier -- 注意这里需要加上 '@'
}, function(title)
playerTitles[targetServerId] = title or '' -- 改为使用targetServerId缓存每个玩家的头衔
TriggerClientEvent('custom_title:updatePlayerTitles', -1, playerTitles)
cb(title)
end)
else
cb(nil)
end
end)
-- 管理员命令设置头衔
RegisterCommand('settitle', function(source, args)
local xPlayer = ESX.GetPlayerFromId(source)
-- 检查管理员权限
if xPlayer.getGroup() ~= 'admin' then
xPlayer.showNotification('~r~你没有权限使用此命令!')
return
end
-- 确保参数完整
local targetId = tonumber(args[1]) -- 玩家ID
local newTitle = table.concat(args, " ", 2) -- 新头衔
if not targetId or not newTitle or newTitle == "" then
xPlayer.showNotification('~r~用法:/settitle <playerId> <newTitle>')
return
end
-- 获取目标玩家
local targetPlayer = ESX.GetPlayerFromId(targetId)
if not targetPlayer then
xPlayer.showNotification('~r~找不到该玩家!')
return
end
-- 更新数据库中的头衔
MySQL.Async.execute('UPDATE users SET title = @title WHERE identifier = @identifier', {
['@title'] = newTitle, -- 注意这里需要加上 '@'
['@identifier'] = targetPlayer.identifier -- 同样也需要加上 '@'
}, function(rowsChanged)
if rowsChanged > 0 then
-- 更新缓存
playerTitles[targetId] = newTitle -- 改为使用targetId来更新缓存
TriggerClientEvent('custom_title:updatePlayerTitles', -1, playerTitles)
-- 通知目标玩家和管理员
targetPlayer.showNotification('~g~你的头衔已被设置为:~s~' .. newTitle)
xPlayer.showNotification('~g~成功设置玩家的头衔为:~s~' .. newTitle)
else
xPlayer.showNotification('~r~设置头衔失败,请检查数据库!')
end
end)
end, false)
### 修改点说明:
1. **使用 `@` 符号**: 在MySQL查询中,必须使用`['@identifier']`和`['@title']`来标识参数。这是因为Lua表键需要以字符串形式定义。
2. **缓存管理**: 我将`playerTitles`的更新逻辑修改为使用玩家的ID (`targetId`) 来保存每个玩家的头衔,而不是覆盖整个`playerTitles`变量。
3. **参数获取**: 在解析指令参数时,需要确保索引从1开始,即`args[1]`用于获取目标玩家的ID。
请将该代码放入你的`server.lua`文件中,并确保你已经正确设置了数据库连接及相关依赖。 |