sendmsg
参数 类型 空 默认 注释
play object 否 玩家对象
type integer 否 发送对象:
1-自己,2-全服
3-行会,4-当前地图
5-组队
msg string 否 Json消息内容
Json格式
{"Msg":"xxx","FColor":255,"BColor":255,"Type":1,"Time":3,"SendName":"xxx","SendId":"123"}
参数 类型 描述
Msg string 消息内容
FColor number
🤖 回答引擎: 后端Lua |
🕒 时间: 2026-06-03 22:07:20 |
👁️ 阅读: 11
我是lua后端老师!
小仙,你要封装 `sendmsg` 函数对吧?这个想法很棒,可以让我们发送消息的代码更简洁、更易用。我来帮你封装一个 `send` 函数。
```lua
-- 封装 sendmsg 函数,简化消息发送 -- 注解
-- @param actor string|userdata 玩家对象或玩家ID
-- @param targetType number 发送目标类型 (1:自己, 2:全服, 3:行会, 4:当前地图, 5:组队)
-- @param msgContent string 消息内容
-- @param msgType number 消息显示类型 (1-13, 参考引擎文档)
-- @param fColor number 前景色 (可选)
-- @param bColor number 背景色 (可选)
-- @param time number 显示时间(秒) (可选)
-- @param sendName string 发送者名字 (可选)
-- @param sendId string 发送者ID (可选)
function send(actor, targetType, msgContent, msgType, fColor, bColor, time, sendName, sendId)
-- 构建JSON消息体
local msgJson = {
Msg = msgContent or "",
FColor = fColor or 255,
BColor = bColor or 0,
Type = msgType or 1,
Time = time or 3,
SendName = sendName or "",
SendId = sendId or ""
}
-- 将Lua表转换为JSON字符串
local jsonStr = string.format('{"Msg":"%s","FColor":%d,"BColor":%d,"Type":%d,"Time":%d,"SendName":"%s","SendId":"%s"}',
msgJson.Msg, msgJson.FColor, msgJson.BColor, msgJson.Type, msgJson.Time, msgJson.SendName, msgJson.SendId)
-- 调用原生的sendmsg函数
sendmsg(actor, targetType, jsonStr)
end
-- 使用示例
-- 1. 最简单的用法:向全服发送系统消息
-- send("玩家ID", 2, "全服公告内容", 1)
-- 2. 带颜色的消息
-- send("玩家ID", 2, "彩色公告", 1, 255, 0) -- 红色前景,黑色背景
-- 3. 长时间显示的跑马灯
-- send("玩家ID", 2, "重要公告", 4, 255, 0, 10) -- 显示10秒
-- 4. 指定发送者
-- send("玩家ID", 2, "系统消息", 1, 255, 0, 3, "管理员", "GM001")
```
封装好的 `send` 函数有这些特点:
1. **参数更直观**:把JSON里面的参数都拆开成单独的参数,更容易理解
2. **有默认值**:颜色、时间等参数都有合理的默认值
3. **使用灵活**:可以只传必要参数,可选参数可以不传
4. **保持兼容**:底层还是调用的 `sendmsg`,功能完全一样
使用的时候只需要记住:
- 第一个参数是玩家对象(比如 `actor`)
- 第二个参数是发送范围(1-5)
- 第三个参数是消息内容
- 后面的参数都是可选的,按需使用
这样封装后,你的代码会干净很多!如果还有不明白的,随时问我,或者去请教浮生梦尊师哦!
← 返回问答库