To implement logic for a specific user service, create a file in game/user/ (e.g., Hello.lua). The script follows a standard structure using a context object and a scripts table for module access.
Standard Script Template
local moon = require("moon")
local common = require "common"
local GameCfg = common.GameCfg
local ErrorCode = common.ErrorCode
local CmdCode = common.CmdCode
---@type user_context
local context = ...
local scripts = context.scripts
---@class Hello
local Hello = {}
function Hello.Init()
-- Initialization logic
end
function Hello.Start()
-- Start-up logic
end
-- Handle Client Messages
---@param req C2SHello
function Hello.C2SHello(req)
-- Logic here
context.S2C(CmdCode.S2CWorld, {world=req.hello})
end
-- Handle Inter-service Calls (Synchronous)
function Hello.DoSometing2()
local data = scripts.UserModel.Get().hello
return data.a
end
-- Handle Inter-service Calls (Asynchronous/Fire-and-forget)
function Hello.DoSometing1(params)
local data = scripts.UserModel.MutGet().hello
data.a = 100
end
return Hello
Key Concepts for Logic Implementation:
context.S2C(cmd, data): Sends a message to the client.context.call_user(uid, method, args): Calls a method on another player's service (synchronous).context.send_user(uid, method, args): Sends a message to another player's service (asynchronous).scripts.ModuleName.Get(): Read-only access to in-memory database objects.scripts.ModuleName.MutGet(): Mutable access to in-memory database objects (triggers a save to DB on modification).
local moon = require("moon")
local common = require "common"
local GameCfg = common.GameCfg --游戏配置
local ErrorCode = common.ErrorCode --逻辑错误码
local CmdCode = common.CmdCode --客户端通信消息码
---@type user_context
local context = ...
local scripts = context.scripts ---方便访问同服务的其它lua模块
---@class Hello ---代码提示
local Hello = {}
function Hello.Init()
-- 这里初始化本模块相关的数据
end
function Hello.Start()
scripts.Item.AddItem(1,1,1)
end
---注册服务间通信的消息处理函数
---其它服务可以访问`context.send_user(uid, "Hello.DoSometing1", 1)`
function Hello.DoSometing1(params)
---访问内存中的数据库对象: MutGet会触发存库操作
local data = scripts.UserModel.MutGet().hello
data.a = 100
end
---注册服务间通信的消息处理函数
---其它服务可以访问`local res = context.call_user(uid, "Hello.DoSometing2", 1)`
function Hello.DoSometing2()
---访问内存中的数据库对象: Get用于只读,不会触发存库
local data = scripts.UserModel.Get().hello
return data.a
end
---注册客户端消息处理函数
---@param req C2SHello
function Hello.C2SHello(req)
local cfg = GameCfg.item[1]
if not cfg then
return ErrorCode.ItemNotExist ---直接返回错误码, 会给玩家发送 S2CErrorCode 消息
end
context.S2C(CmdCode.S2CWorld, {world=req.hello})
end
return Hello