全局函数 (Global)

数据库操作函数

WorldDBQuery
在世界数据库上执行SQL查询并返回查询结果
WorldDBQuery(sql)

参数

sql (string)
要执行的SQL查询语句

返回值

ElunaQuery - 查询结果对象,如果查询失败则返回nil

示例

-- 查询所有玩家角色 local query = WorldDBQuery("SELECT entry, name FROM creature_template WHERE type = 7") if query then repeat local entry = query:GetUInt32(0) local name = query:GetString(1) print("NPC ID: " .. entry .. ", 名称: " .. name) until not query:NextRow() end
WorldDBExecute
在世界数据库上执行SQL语句(INSERT、UPDATE、DELETE等)
WorldDBExecute(sql)

参数

sql (string)
要执行的SQL语句

返回值

boolean - 执行成功返回true,失败返回false

示例

-- 更新NPC的生命值 local success = WorldDBExecute("UPDATE creature_template SET HealthModifier = 2.0 WHERE entry = 1234") if success then print("NPC生命值更新成功") else print("更新失败") end
CharDBQuery
在角色数据库上执行SQL查询并返回查询结果
CharDBQuery(sql)

参数

sql (string)
要执行的SQL查询语句

返回值

ElunaQuery - 查询结果对象,如果查询失败则返回nil

示例

-- 查询在线玩家数量 local query = CharDBQuery("SELECT COUNT(*) FROM characters WHERE online = 1") if query then local count = query:GetUInt32(0) print("当前在线玩家数量: " .. count) end

玩家管理函数

GetPlayerByName
根据玩家名称查找并返回玩家对象
GetPlayerByName(name)

参数

name (string)
玩家角色名称

返回值

Player - 玩家对象,如果未找到则返回nil

示例

-- 查找指定玩家并发送消息 local player = GetPlayerByName("PlayerName") if player then player:SendBroadcastMessage("你好," .. player:GetName() .. "!") else print("未找到玩家") end
GetPlayerCount
获取当前在线玩家数量
GetPlayerCount()

参数

无参数

返回值

number - 当前在线玩家数量

示例

-- 获取并显示在线玩家数量 local count = GetPlayerCount() print("当前在线玩家数量: " .. count)
SendWorldMessage
向所有在线玩家发送全服消息
SendWorldMessage(message)

参数

message (string)
要发送的消息内容

返回值

无返回值

示例

-- 发送全服公告 SendWorldMessage("服务器将在10分钟后重启,请做好准备!")

时间和事件函数

GetCurrTime
获取当前服务器时间戳
GetCurrTime()

参数

无参数

返回值

number - 当前时间戳(秒)

示例

-- 记录当前时间 local currentTime = GetCurrTime() print("当前时间戳: " .. currentTime)
CreateLuaEvent
创建一个定时执行的LUA事件
CreateLuaEvent(function, delay, repeats)

参数

function (function)
要执行的函数
delay (number)
延迟时间(毫秒)
repeats (number)
重复次数,0表示无限重复

返回值

number - 事件ID,用于取消事件

示例

-- 创建一个每30秒执行一次的事件 local eventId = CreateLuaEvent(function() SendWorldMessage("定时公告:欢迎来到我们的服务器!") end, 30000, 0) print("定时事件已创建,ID: " .. eventId)
RemoveLuaEvent
移除指定的LUA事件
RemoveLuaEvent(eventId)

参数

eventId (number)
要移除的事件ID

返回值

无返回值

示例

-- 创建事件并在条件满足时移除 local eventId = CreateLuaEvent(function() local playerCount = GetPlayerCount() if playerCount == 0 then RemoveLuaEvent(eventId) print("没有玩家在线,停止定时事件") else SendWorldMessage("当前在线玩家: " .. playerCount) end end, 60000, 0)

对象创建和管理函数

CreateItem
创建一个物品对象
CreateItem(itemId, count)

参数

itemId (number)
物品ID
count (number)
物品数量,可选参数,默认为1

返回值

Item - 创建的物品对象,失败返回nil

示例

-- 创建物品并检查属性 local item = CreateItem(6948, 1) -- 创建炉石 if item then print("创建物品成功: " .. item:GetName()) print("物品品质: " .. item:GetQuality()) else print("创建物品失败") end
SpawnObject
在指定位置生成游戏对象
SpawnObject(entry, x, y, z, o, mapId)

参数

entry (number)
对象模板ID
x, y, z (number)
坐标位置
o (number)
朝向角度
mapId (number)
地图ID

返回值

GameObject - 生成的游戏对象

示例

-- 在暴风城生成一个宝箱 local chest = SpawnObject(123456, -8949.95, -132.493, 83.5312, 0, 0) if chest then print("宝箱生成成功") end

事件注册函数

RegisterPlayerEvent
注册玩家事件监听器
RegisterPlayerEvent(eventId, function)

参数

eventId (number)
事件ID(如:3=登录,4=登出,13=升级等)
function (function)
事件处理函数

返回值

无返回值

示例

-- 注册玩家登录事件 RegisterPlayerEvent(3, function(event, player) local playerName = player:GetName() local level = player:GetLevel() SendWorldMessage(playerName .. " (等级" .. level .. ") 进入了游戏!") end) -- 注册玩家升级事件 RegisterPlayerEvent(13, function(event, player, oldLevel) local newLevel = player:GetLevel() player:SendBroadcastMessage("恭喜升级到 " .. newLevel .. " 级!") end)
RegisterCreatureEvent
注册生物事件监听器
RegisterCreatureEvent(entry, eventId, function)

参数

entry (number)
生物模板ID,0表示所有生物
eventId (number)
事件ID(如:1=生成,4=死亡,5=击杀玩家等)
function (function)
事件处理函数

返回值

无返回值

示例

-- 注册BOSS死亡事件 RegisterCreatureEvent(12345, 4, function(event, creature, killer) if killer and killer:IsPlayer() then local player = killer:ToPlayer() SendWorldMessage(player:GetName() .. " 击败了强大的BOSS!") -- 给予特殊奖励 player:AddItem(12345, 1) -- 特殊物品 player:ModifyMoney(1000000) -- 100金币 end end)
RegisterServerEvent
注册服务器事件监听器
RegisterServerEvent(eventId, function)

参数

eventId (number)
事件ID(如:33=服务器启动,34=服务器关闭等)
function (function)
事件处理函数

返回值

无返回值

示例

-- 注册服务器启动事件 RegisterServerEvent(33, function() print("服务器启动完成,LUA脚本系统已加载") -- 延迟30秒后发送欢迎消息 CreateLuaEvent(function() SendWorldMessage("服务器已完全启动,欢迎大家!") end, 30000, 1) end)

实用工具函数

GetGameTime
获取游戏世界时间
GetGameTime()

参数

无参数

返回值

number - 游戏时间(秒)

示例

-- 获取游戏时间并格式化显示 local gameTime = GetGameTime() local hours = math.floor(gameTime / 3600) % 24 local minutes = math.floor(gameTime / 60) % 60 print(string.format("游戏时间: %02d:%02d", hours, minutes)) -- 根据游戏时间执行不同逻辑 if hours >= 6 and hours < 18 then print("现在是白天") else print("现在是夜晚") end
PerformIngameQuery
执行游戏内查询操作
PerformIngameQuery(queryType, ...)

参数

queryType (number)
查询类型
... (various)
查询参数

返回值

various - 根据查询类型返回不同结果

示例

-- 查询服务器统计信息 local uptime = PerformIngameQuery(1) -- 服务器运行时间 local maxPlayers = PerformIngameQuery(2) -- 最大玩家数 local currentPlayers = GetPlayerCount() print("服务器运行时间: " .. uptime .. " 秒") print("在线玩家: " .. currentPlayers .. "/" .. maxPlayers)
ReloadTable
重新加载指定的数据库表
ReloadTable(tableName)

参数

tableName (string)
要重新加载的表名

返回值

boolean - 成功返回true,失败返回false

示例

-- 重新加载配置表 if ReloadTable("creature_template") then SendWorldMessage("生物模板已重新加载") else print("重新加载失败") end -- 批量重新加载多个表 local tables = {"item_template", "quest_template", "spell_template"} for _, tableName in ipairs(tables) do if ReloadTable(tableName) then print(tableName .. " 重新加载成功") end end
KickPlayer
踢出指定玩家
KickPlayer(player, reason)

参数

player (Player)
要踢出的玩家对象
reason (string)
踢出原因,可选参数

返回值

无返回值

示例

-- 踢出违规玩家 local function CheckPlayerBehavior(player) local playerName = player:GetName() -- 检查玩家等级是否异常 if player:GetLevel() > 80 then KickPlayer(player, "等级异常") print("玩家 " .. playerName .. " 因等级异常被踢出") return end -- 检查玩家位置是否在禁区 local x, y, z = player:GetX(), player:GetY(), player:GetZ() if x > 10000 or y > 10000 then KickPlayer(player, "位置异常") print("玩家 " .. playerName .. " 因位置异常被踢出") end end
BanPlayer
封禁指定玩家账号
BanPlayer(player, duration, reason)

参数

player (Player)
要封禁的玩家对象
duration (number)
封禁时长(秒),0表示永久封禁
reason (string)
封禁原因

返回值

boolean - 成功返回true,失败返回false

示例

-- 自动封禁系统 local function AutoBanSystem(player, violationType) local playerName = player:GetName() local banDuration = 0 local reason = "" if violationType == "cheat" then banDuration = 86400 * 7 -- 7天 reason = "使用作弊工具" elseif violationType == "spam" then banDuration = 3600 * 24 -- 24小时 reason = "恶意刷屏" elseif violationType == "exploit" then banDuration = 0 -- 永久封禁 reason = "利用游戏漏洞" end if BanPlayer(player, banDuration, reason) then SendWorldMessage("玩家 " .. playerName .. " 因 " .. reason .. " 被封禁") print("封禁成功: " .. playerName .. " - " .. reason) end end
SpawnObject
在指定位置生成游戏对象
SpawnObject(entry, x, y, z, o, mapId, respawnTime)

参数

entry (number)
游戏对象模板ID
x, y, z (number)
坐标位置
o (number)
朝向角度
mapId (number)
地图ID
respawnTime (number)
重生时间(秒),可选

返回值

GameObject - 生成的游戏对象,失败返回nil

示例

-- 生成一个宝箱 local chest = SpawnObject(123456, -8949.95, -132.493, 83.5312, 0, 0, 300) if chest then print("宝箱生成成功,5分钟后重生") end
SpawnCreature
在指定位置生成生物
SpawnCreature(entry, x, y, z, o, mapId, respawnTime)

参数

entry (number)
生物模板ID
x, y, z (number)
坐标位置
o (number)
朝向角度
mapId (number)
地图ID
respawnTime (number)
重生时间(秒),可选

返回值

Creature - 生成的生物对象,失败返回nil

示例

-- 生成一个守卫NPC local guard = SpawnCreature(1423, -8949.95, -132.493, 83.5312, 0, 0, 600) if guard then guard:SendUnitSay("我是新生成的守卫!", 0) end
GetPlayerByAccountId
根据账号ID查找玩家
GetPlayerByAccountId(accountId)

参数

accountId (number)
账号ID

返回值

Player - 玩家对象,如果未找到则返回nil

示例

-- 根据账号ID查找玩家并发送消息 local player = GetPlayerByAccountId(12345) if player then player:SendBroadcastMessage("系统消息:你的账号有重要通知!") end
GetPlayerByGUID
根据GUID查找玩家
GetPlayerByGUID(guid)

参数

guid (number)
玩家GUID

返回值

Player - 玩家对象,如果未找到则返回nil

示例

-- 根据GUID查找玩家 local playerGuid = 123456789 local player = GetPlayerByGUID(playerGuid) if player then print("找到玩家: " .. player:GetName()) end

地图和传送函数

GetMapId
获取指定对象所在的地图ID
GetMapId(object)

参数

object (WorldObject)
世界对象(玩家、生物等)

返回值

number - 地图ID

示例

-- 检查玩家所在地图并给予相应提示 local function CheckPlayerLocation(player) local mapId = GetMapId(player) local mapNames = { [0] = "东部王国", [1] = "卡利姆多", [530] = "外域", [571] = "诺森德", [609] = "永恒之眼", [249] = "奥妮克希亚的巢穴" } local mapName = mapNames[mapId] or ("地图" .. mapId) player:SendBroadcastMessage("当前位置: " .. mapName) -- 根据地图给予不同提示 if mapId == 530 then player:SendBroadcastMessage("欢迎来到外域!小心恶魔!") elseif mapId == 571 then player:SendBroadcastMessage("诺森德的寒风刺骨,注意保暖!") end end
TeleportPlayer
传送玩家到指定位置
TeleportPlayer(player, mapId, x, y, z, o)

参数

player (Player)
要传送的玩家
mapId (number)
目标地图ID
x, y, z (number)
目标坐标
o (number)
朝向角度

返回值

boolean - 传送成功返回true

示例

-- 快速传送系统 local teleportLocations = { ["暴风城"] = {0, -8949.95, -132.493, 83.5312, 0}, ["奥格瑞玛"] = {1, 1676.21, -4315.29, 61.5243, 1.06}, ["铁炉堡"] = {0, -4981.25, -881.542, 501.66, 2.16}, ["雷霆崖"] = {1, -1274.45, 71.8601, 128.159, 2.80} } local function QuickTeleport(player, locationName) local location = teleportLocations[locationName] if location then local success = TeleportPlayer(player, location[1], location[2], location[3], location[4], location[5]) if success then player:SendBroadcastMessage("传送到 " .. locationName .. " 成功!") else player:SendBroadcastMessage("传送失败,请稍后再试") end else player:SendBroadcastMessage("未知的传送位置: " .. locationName) end end
GetZoneId
获取指定对象所在的区域ID
GetZoneId(object)

参数

object (WorldObject)
世界对象

返回值

number - 区域ID

示例

-- 区域特殊事件系统 local function CheckZoneEvents(player) local zoneId = GetZoneId(player) local zoneNames = { [1519] = "暴风城", [1637] = "奥格瑞玛", [1537] = "铁炉堡", [1638] = "雷霆崖", [1657] = "达纳苏斯", [1497] = "幽暗城" } local zoneName = zoneNames[zoneId] or ("区域" .. zoneId) -- 主城特殊福利 if zoneId == 1519 or zoneId == 1637 then -- 暴风城或奥格瑞玛 player:SendBroadcastMessage("欢迎来到主城!获得休息经验加成!") -- 可以在这里添加经验加成逻辑 end -- 危险区域警告 local dangerousZones = {1377, 1377, 2017} -- 一些危险区域ID for _, dangerZone in ipairs(dangerousZones) do if zoneId == dangerZone then player:SendBroadcastMessage("警告:你进入了危险区域!") break end end end

服务器管理函数

GetServerStatus
获取服务器运行状态信息
GetServerStatus()

参数

无参数

返回值

table - 包含服务器状态信息的表

示例

-- 服务器状态监控 local function ShowServerStatus(player) local status = GetServerStatus() if status then player:SendBroadcastMessage("=== 服务器状态 ===") player:SendBroadcastMessage("在线玩家: " .. (status.playerCount or 0)) player:SendBroadcastMessage("运行时间: " .. (status.uptime or "未知")) player:SendBroadcastMessage("服务器版本: " .. (status.version or "未知")) -- 性能警告 if status.playerCount and status.playerCount > 1000 then player:SendBroadcastMessage("服务器负载较高,可能出现延迟") end else player:SendBroadcastMessage("无法获取服务器状态信息") end end
ReloadConfig
重新加载服务器配置文件
ReloadConfig(configType)

参数

configType (string)
配置类型(可选)

返回值

boolean - 重载成功返回true

示例

-- 管理员配置重载命令 local function AdminReloadConfig(player, configType) -- 检查管理员权限 if not player:IsGM() then player:SendBroadcastMessage("权限不足:需要管理员权限") return end local success = ReloadConfig(configType) if success then player:SendBroadcastMessage("配置重载成功: " .. (configType or "全部")) SendWorldMessage("管理员重载了服务器配置") else player:SendBroadcastMessage("配置重载失败") end end
SaveAllPlayers
保存所有在线玩家数据
SaveAllPlayers()

参数

无参数

返回值

number - 保存的玩家数量

示例

-- 定期自动保存系统 local function AutoSaveSystem() local savedCount = SaveAllPlayers() SendWorldMessage("自动保存完成,已保存 " .. savedCount .. " 个玩家数据") -- 记录保存日志 print("[AutoSave] " .. GetCurrTime() .. " - Saved " .. savedCount .. " players") end -- 每30分钟自动保存一次 CreateLuaEvent(AutoSaveSystem, 1800000, 0) -- 30分钟 = 1800000毫秒

事件注册和处理函数

RegisterPlayerEvent
注册玩家事件处理函数
RegisterPlayerEvent(eventId, function)

参数

eventId (number)
事件ID(如登录、升级、死亡等)
function (function)
事件处理函数

返回值

无返回值

示例

-- 注册玩家登录事件 RegisterPlayerEvent(3, function(event, player) -- PLAYER_EVENT_ON_LOGIN = 3 player:SendBroadcastMessage("欢迎回到游戏世界!") -- 检查玩家等级并给予奖励 local level = player:GetLevel() if level >= 60 then player:SendBroadcastMessage("满级玩家福利:获得额外金币!") player:ModifyMoney(100000) -- 10金币 end -- 记录登录日志 local playerName = player:GetName() print("[LOGIN] " .. playerName .. " 已登录服务器") end) -- 注册玩家升级事件 RegisterPlayerEvent(13, function(event, player, oldLevel) -- PLAYER_EVENT_ON_LEVEL_CHANGE = 13 local newLevel = player:GetLevel() player:SendBroadcastMessage("恭喜升级到 " .. newLevel .. " 级!") -- 升级奖励 if newLevel % 10 == 0 then -- 每10级 player:AddItem(6948, 1) -- 炉石 player:SendBroadcastMessage("达到" .. newLevel .. "级里程碑!获得特殊奖励!") end end)
RegisterCreatureEvent
注册生物事件处理函数
RegisterCreatureEvent(entry, eventId, function)

参数

entry (number)
生物模板ID,0表示所有生物
eventId (number)
事件ID
function (function)
事件处理函数

返回值

无返回值

示例

-- 注册特定NPC的对话事件 RegisterCreatureEvent(1234, 1, function(event, creature, player) -- CREATURE_EVENT_ON_GOSSIP_HELLO = 1 local playerLevel = player:GetLevel() if playerLevel < 10 then player:GossipMenuAddItem(0, "我是新手,需要帮助", 1, 0) else player:GossipMenuAddItem(0, "我想要传送服务", 2, 0) player:GossipMenuAddItem(0, "查看商店", 3, 0) end player:GossipSendMenu(1, creature) end) -- 注册生物死亡事件 RegisterCreatureEvent(0, 4, function(event, creature, killer) -- CREATURE_EVENT_ON_DIED = 4 if killer and killer:IsPlayer() then local player = killer:ToPlayer() local entry = creature:GetEntry() -- 特殊BOSS额外奖励 local bossList = {12345, 12346, 12347} for _, bossEntry in ipairs(bossList) do if entry == bossEntry then player:SendBroadcastMessage("击败了强大的BOSS!获得额外奖励!") player:AddItem(99999, 1) -- 特殊奖励物品 break end end end end)
RegisterServerEvent
注册服务器级别事件
RegisterServerEvent(eventId, function)

参数

eventId (number)
服务器事件ID
function (function)
事件处理函数

返回值

无返回值

示例

-- 注册服务器启动事件 RegisterServerEvent(33, function(event) -- SERVER_EVENT_ON_STARTUP = 33 print("[SERVER] 服务器启动完成,开始加载自定义功能...") -- 初始化全局变量 ServerStartTime = GetCurrTime() -- 启动定时任务 CreateLuaEvent(function() SendWorldMessage("服务器运行正常,当前在线玩家: " .. GetPlayerCount()) end, 3600000, 0) -- 每小时广播一次 print("[SERVER] 自定义功能加载完成") end) -- 注册服务器关闭事件 RegisterServerEvent(34, function(event) -- SERVER_EVENT_ON_SHUTDOWN = 34 print("[SERVER] 服务器准备关闭,保存重要数据...") -- 保存所有玩家数据 SaveAllPlayers() -- 发送关闭通知 SendWorldMessage("服务器将在1分钟后关闭,请及时下线保存数据!") print("[SERVER] 数据保存完成,服务器可以安全关闭") end)
RegisterItemEvent
注册物品使用事件
RegisterItemEvent(entry, eventId, function)

参数

entry (number)
物品模板ID
eventId (number)
事件ID
function (function)
事件处理函数

返回值

无返回值

示例

-- 注册自定义物品使用事件 RegisterItemEvent(99999, 1, function(event, player, item) -- ITEM_EVENT_ON_USE = 1 local itemName = item:GetName() player:SendBroadcastMessage("使用了特殊物品: " .. itemName) -- 随机传送效果 local locations = { {0, -8949.95, -132.493, 83.5312, 0}, -- 暴风城 {1, 1676.21, -4315.29, 61.5243, 1.06}, -- 奥格瑞玛 {0, -4981.25, -881.542, 501.66, 2.16} -- 铁炉堡 } local randomLoc = locations[math.random(1, #locations)] player:Teleport(randomLoc[1], randomLoc[2], randomLoc[3], randomLoc[4], randomLoc[5]) player:SendBroadcastMessage("随机传送激活!") -- 消耗物品 player:RemoveItem(99999, 1) return false -- 阻止默认使用效果 end)

游戏对象管理函数

GetCreatureByEntry
根据模板ID获取生物对象
GetCreatureByEntry(entry)

参数

entry (number)
生物模板ID

返回值

Creature - 生物对象,未找到返回nil

示例

-- 查找并控制特定NPC local function ControlSpecialNPC() local npc = GetCreatureByEntry(12345) -- 特殊NPC ID if npc then npc:SendUnitSay("我被脚本控制了!", 0) npc:SetFaction(35) -- 设置为友善 -- 让NPC移动到指定位置 npc:MoveTo(1, -8949.95, -132.493, 83.5312) print("成功控制NPC: " .. npc:GetName()) else print("未找到指定的NPC") end end -- 定时检查BOSS状态 CreateLuaEvent(function() local boss = GetCreatureByEntry(99999) -- BOSS ID if boss and boss:IsAlive() then local healthPercent = (boss:GetHealth() / boss:GetMaxHealth()) * 100 if healthPercent < 10 then SendWorldMessage("警告:BOSS血量不足10%,即将进入狂暴状态!") end end end, 30000, 0) -- 每30秒检查一次
GetGameObjectByEntry
根据模板ID获取游戏对象
GetGameObjectByEntry(entry)

参数

entry (number)
游戏对象模板ID

返回值

GameObject - 游戏对象,未找到返回nil

示例

-- 控制特殊游戏对象 local function ControlSpecialObject() local chest = GetGameObjectByEntry(123456) -- 宝箱ID if chest then -- 设置宝箱状态 chest:SetGoState(0) -- 关闭状态 -- 定时开启宝箱 CreateLuaEvent(function() if chest:IsInWorld() then chest:SetGoState(1) -- 开启状态 SendWorldMessage("神秘宝箱已开启!快去寻找宝藏!") end end, 60000, 1) -- 1分钟后开启 print("成功控制游戏对象") else print("未找到指定的游戏对象") end end -- 传送门管理系统 local function ManagePortals() local portal = GetGameObjectByEntry(654321) -- 传送门ID if portal then -- 每小时随机改变传送门目标 CreateLuaEvent(function() local destinations = { "暴风城", "奥格瑞玛", "铁炉堡", "雷霆崖" } local randomDest = destinations[math.random(1, #destinations)] SendWorldMessage("传送门目标已更改为: " .. randomDest) end, 3600000, 0) -- 每小时执行 end end

高级数据库操作函数

AuthDBQuery
执行认证数据库查询
AuthDBQuery(sql)

参数

sql (string)
SQL查询语句

返回值

QueryResult - 查询结果对象

示例

-- 账号管理系统 local function GetAccountInfo(accountName) local query = string.format("SELECT id, username, email, joindate FROM account WHERE username = '%s'", accountName) local result = AuthDBQuery(query) if result then local accountId = result:GetUInt32(0) local username = result:GetString(1) local email = result:GetString(2) local joinDate = result:GetString(3) return { id = accountId, username = username, email = email, joinDate = joinDate } end return nil end -- 账号安全检查 local function CheckAccountSecurity(player) local accountId = player:GetAccountId() local query = string.format("SELECT gmlevel, last_ip FROM account WHERE id = %d", accountId) local result = AuthDBQuery(query) if result then local gmLevel = result:GetUInt8(0) local lastIP = result:GetString(1) if gmLevel > 0 then player:SendBroadcastMessage("管理员账号,权限等级: " .. gmLevel) end player:SendBroadcastMessage("上次登录IP: " .. lastIP) end end -- 在线时间统计 local function UpdateOnlineTime(player) local accountId = player:GetAccountId() local currentTime = os.time() local query = string.format( "UPDATE account SET totaltime = totaltime + %d WHERE id = %d", 300, accountId -- 增加5分钟在线时间 ) AuthDBExecute(query) end
AuthDBExecute
执行认证数据库更新操作
AuthDBExecute(sql)

参数

sql (string)
SQL执行语句

返回值

boolean - 执行成功返回true

示例

-- 账号封禁系统 local function BanAccount(accountName, reason, duration) local banUntil = os.time() + duration local query = string.format( "UPDATE account SET banned = 1, bandate = %d, unbandate = %d, banreason = '%s' WHERE username = '%s'", os.time(), banUntil, reason, accountName ) local success = AuthDBExecute(query) if success then print("[BAN] 账号 " .. accountName .. " 已被封禁,原因: " .. reason) -- 踢出在线玩家 local player = GetPlayerByName(accountName) if player then player:SendBroadcastMessage("你的账号已被封禁: " .. reason) player:KickPlayer() end end return success end -- VIP系统 local function SetVIPStatus(accountId, vipLevel, duration) local expireTime = os.time() + duration local query = string.format( "UPDATE account SET vip_level = %d, vip_expire = %d WHERE id = %d", vipLevel, expireTime, accountId ) local success = AuthDBExecute(query) if success then local player = GetPlayerByAccountId(accountId) if player then player:SendBroadcastMessage("恭喜!你的VIP等级已提升至 " .. vipLevel) end end return success end -- 账号数据清理 local function CleanupInactiveAccounts() local thirtyDaysAgo = os.time() - (30 * 24 * 3600) local query = string.format( "DELETE FROM account WHERE last_login < %d AND gmlevel = 0", thirtyDaysAgo ) local success = AuthDBExecute(query) if success then print("[CLEANUP] 已清理30天未登录的普通账号") end end
LogDBQuery
执行日志数据库查询
LogDBQuery(sql)

参数

sql (string)
SQL查询语句

返回值

QueryResult - 查询结果对象

示例

-- 玩家行为分析 local function AnalyzePlayerBehavior(playerGuid) local query = string.format( "SELECT action_type, COUNT(*) as count FROM player_logs WHERE player_guid = %d GROUP BY action_type", playerGuid ) local result = LogDBQuery(query) local behaviors = {} if result then repeat local actionType = result:GetString(0) local count = result:GetUInt32(1) behaviors[actionType] = count until not result:NextRow() end return behaviors end -- 服务器统计报告 local function GenerateServerReport() local queries = { ["total_logins"] = "SELECT COUNT(*) FROM login_logs WHERE DATE(login_time) = CURDATE()", ["unique_players"] = "SELECT COUNT(DISTINCT player_guid) FROM player_logs WHERE DATE(log_time) = CURDATE()", ["total_deaths"] = "SELECT COUNT(*) FROM death_logs WHERE DATE(death_time) = CURDATE()" } local report = {} for key, query in pairs(queries) do local result = LogDBQuery(query) if result then report[key] = result:GetUInt32(0) end end return report end -- 异常行为检测 local function DetectAbnormalBehavior() local query = [[ SELECT player_guid, COUNT(*) as action_count FROM player_logs WHERE log_time > DATE_SUB(NOW(), INTERVAL 1 HOUR) GROUP BY player_guid HAVING action_count > 1000 ]] local result = LogDBQuery(query) local suspiciousPlayers = {} if result then repeat local playerGuid = result:GetUInt32(0) local actionCount = result:GetUInt32(1) table.insert(suspiciousPlayers, {guid = playerGuid, actions = actionCount}) until not result:NextRow() end return suspiciousPlayers end

系统监控和性能函数

GetServerInfo
获取详细的服务器信息
GetServerInfo()

参数

无参数

返回值

table - 包含服务器详细信息的表

示例

-- 服务器监控系统 local function ServerMonitoring() local info = GetServerInfo() if info then local report = { "=== 服务器状态报告 ===", "在线玩家: " .. (info.playerCount or 0), "运行时间: " .. (info.uptime or "未知"), "CPU使用率: " .. (info.cpuUsage or "未知") .. "%", "内存使用: " .. (info.memoryUsage or "未知") .. "MB", "网络延迟: " .. (info.avgLatency or "未知") .. "ms" } -- 性能警告 if info.cpuUsage and info.cpuUsage > 80 then table.insert(report, "⚠️ 警告:CPU使用率过高!") end if info.memoryUsage and info.memoryUsage > 2048 then table.insert(report, "⚠️ 警告:内存使用量过高!") end if info.playerCount and info.playerCount > 500 then table.insert(report, "⚠️ 注意:在线玩家数量较多,注意服务器负载") end -- 发送报告给管理员 for _, line in ipairs(report) do print("[MONITOR] " .. line) end return info end return nil end -- 自动性能优化 local function AutoPerformanceOptimization() local info = GetServerInfo() if info and info.cpuUsage and info.cpuUsage > 90 then -- CPU使用率过高时的优化措施 print("[OPTIMIZATION] CPU使用率过高,启动优化措施") -- 减少非必要的定时任务 -- 临时降低某些功能的更新频率 -- 发送警告给在线管理员 local gms = GetOnlineGMs() for _, gm in pairs(gms) do gm:SendBroadcastMessage("系统警告:服务器CPU使用率过高,已启动自动优化") end end end -- 定期监控任务 CreateLuaEvent(function() ServerMonitoring() AutoPerformanceOptimization() end, 300000, 0) -- 每5分钟执行一次
GetMemoryUsage
获取服务器内存使用情况
GetMemoryUsage()

参数

无参数

返回值

table - 内存使用信息

示例

-- 内存监控和管理 local function MemoryManagement() local memory = GetMemoryUsage() if memory then local usedMB = memory.used / 1024 / 1024 local totalMB = memory.total / 1024 / 1024 local usagePercent = (memory.used / memory.total) * 100 print(string.format("[MEMORY] 使用: %.2f MB / %.2f MB (%.1f%%)", usedMB, totalMB, usagePercent)) -- 内存使用率过高时的处理 if usagePercent > 85 then print("[MEMORY] 内存使用率过高,启动清理程序") -- 清理缓存 ClearServerCache() -- 强制垃圾回收 collectgarbage("collect") -- 通知管理员 SendWorldMessage("系统通知:内存使用率过高,已执行自动清理") -- 如果仍然过高,考虑重启服务器 local newMemory = GetMemoryUsage() local newUsagePercent = (newMemory.used / newMemory.total) * 100 if newUsagePercent > 90 then print("[MEMORY] 严重警告:内存使用率仍然过高,建议重启服务器") SendWorldMessage("严重警告:服务器内存不足,建议管理员重启服务器") end end return memory end return nil end -- 内存泄漏检测 local lastMemoryUsage = 0 local memoryIncreaseCount = 0 local function DetectMemoryLeak() local memory = GetMemoryUsage() if memory then local currentUsage = memory.used if currentUsage > lastMemoryUsage then memoryIncreaseCount = memoryIncreaseCount + 1 else memoryIncreaseCount = 0 end -- 连续10次检查内存都在增长,可能存在内存泄漏 if memoryIncreaseCount >= 10 then print("[MEMORY_LEAK] 检测到可能的内存泄漏") SendWorldMessage("系统警告:检测到可能的内存泄漏,请联系管理员") memoryIncreaseCount = 0 end lastMemoryUsage = currentUsage end end

调试和日志函数

PrintDebug
输出调试信息到控制台
PrintDebug(message, level)

参数

message (string)
调试消息内容
level (number)
日志级别,可选参数

返回值

无返回值

示例

-- 调试函数执行过程 local function DebugPlayerLogin(player) PrintDebug("玩家登录开始: " .. player:GetName(), 1) local startTime = GetCurrTime() -- 执行登录逻辑 local level = player:GetLevel() local money = player:GetCoinage() PrintDebug("玩家信息 - 等级: " .. level .. ", 金币: " .. money, 2) -- 检查执行时间 local endTime = GetCurrTime() local executionTime = endTime - startTime if executionTime > 1 then PrintDebug("警告: 登录处理耗时过长 " .. executionTime .. " 秒", 3) else PrintDebug("登录处理完成,耗时: " .. executionTime .. " 秒", 1) end end
LogToFile
将日志信息写入文件
LogToFile(filename, message)

参数

filename (string)
日志文件名
message (string)
要记录的消息

返回值

boolean - 成功返回true,失败返回false

示例

-- 记录重要事件到日志文件 local function LogImportantEvent(eventType, player, details) local timestamp = os.date("%Y-%m-%d %H:%M:%S") local playerName = player and player:GetName() or "Unknown" local playerGUID = player and player:GetGUIDLow() or 0 local logMessage = string.format( "[%s] %s - 玩家: %s (GUID: %d) - 详情: %s", timestamp, eventType, playerName, playerGUID, details ) -- 根据事件类型写入不同日志文件 if eventType == "LEVEL_UP" then LogToFile("level_events.log", logMessage) elseif eventType == "ITEM_RECEIVED" then LogToFile("item_events.log", logMessage) elseif eventType == "SECURITY_VIOLATION" then LogToFile("security.log", logMessage) else LogToFile("general.log", logMessage) end end -- 使用示例 LogImportantEvent("LEVEL_UP", player, "从等级59升到60")
GetServerStats
获取服务器统计信息
GetServerStats()

参数

无参数

返回值

table - 包含服务器统计信息的表

示例

-- 获取并显示服务器统计信息 local function ShowServerStats() local stats = GetServerStats() if stats then print("=== 服务器统计信息 ===") print("运行时间: " .. (stats.uptime or 0) .. " 秒") print("在线玩家: " .. (stats.onlinePlayers or 0)) print("最大玩家数: " .. (stats.maxPlayers or 0)) print("CPU使用率: " .. (stats.cpuUsage or 0) .. "%") print("内存使用: " .. (stats.memoryUsage or 0) .. " MB") print("网络流量: " .. (stats.networkTraffic or 0) .. " KB/s") -- 如果在线玩家过多,发出警告 if stats.onlinePlayers and stats.maxPlayers then local usage = (stats.onlinePlayers / stats.maxPlayers) * 100 if usage > 90 then SendWorldMessage("服务器负载较高,请注意游戏体验") end end else print("无法获取服务器统计信息") end end -- 定期检查服务器状态 CreateLuaEvent(ShowServerStats, 300000, 0) -- 每5分钟检查一次