快速入门¶
GameServer 内置了 Lua 5.4 脚本引擎。脚本通过 BridgeFunctionAttach() 注册事件处理函数,并在启动时通过 ScriptCore.lua 自动加载。
第一个脚本¶
在脚本目录中创建一个名为 Welcome.lua 的文件:
-- Welcome.lua - 玩家登录时发送欢迎消息
local function OnPlayerLogin(aIndex)
local player = GetUser(aIndex)
if player == nil then return end
GCNoticeSend(aIndex, 1, "Welcome to the server, " .. player.Name .. "!")
LogAdd(LOG_GREEN, "[Welcome] " .. player.Name .. " has logged in.")
end
-- 注册处理函数
BridgeFunctionAttach("OnCharacterEntry", OnPlayerLogin)
核心概念¶
事件驱动架构¶
通过 BridgeFunctionAttach() 将处理函数绑定到事件:
BridgeFunctionAttach("OnMonsterDie", function(aIndex, bIndex)
-- 每次怪物死亡时执行
-- aIndex = 怪物, bIndex = 击杀者
end)
GetUser() 函数¶
处理函数接收一个 aIndex(对象索引)。GetUser() 返回完整的对象:
local player = GetUser(aIndex)
if player then
-- 访问属性
print(player.Name) -- 角色名
print(player.Level) -- 当前等级
print(player.Map) -- 当前地图
print(player.Class) -- 角色职业
end
钩子中的返回值¶
部分钩子使用返回值来控制游戏行为:
| 返回值 | 含义 |
|---|---|
0 |
阻止默认行为 |
1 |
允许默认行为 |
BridgeFunctionAttach("OnItemDrop", function(aIndex, slot, item)
if item:IsSetItem() then
GCNoticeSend(aIndex, 1, "You cannot drop Ancient items!")
return 0 -- 阻止丢弃
end
return 1 -- 正常允许
end)
下一步¶
- 脚本结构 — 了解
ScriptCore.lua和BridgeFunctionAttach - 版本兼容性 — 各游戏版本可用的 API
- 服务端 API 参考 — 完整函数参考
- 示例 — 实际脚本示例