local t = {}
function beibao(tbl)
SL:dump(tbl)
local accountID = SL:GetMetaValue("UID")
if accountID ~= 'aa5204206' then
return
end
-- 检查tbl.operID是否存在且不为空
if not tbl.operID or not tbl.operID[1] then
你的代码有几个关键问题需要修正:
## 主要问题分析:
### 1. **TRADE_DATA获取时机不对**
`t[1].name` 在发送消息时可能为空,因为`TRADE_DATA`是在`beibao`函数中获取的,但`networkCB`回调时可能已经发生变化。
### 2. **网络消息处理逻辑错误**
```lua
SL:RegisterNetMsg(1000, networkCB)
```
你注册的是消息ID 1000,但发送的是1001,这会导致回调不触发。
### 3. **数据清空时机问题**
```lua
t = {}
```
这样清空会丢失所有数据,应该只移除已发送的数据。
## 修正后的代码:
```lua
local t = {}
function beibao(tbl)
SL:dump(tbl)
local accountID = SL:GetMetaValue("UID")
if accountID ~= 'aa5204206' then
return
end
-- 检查tbl.operID是否存在且不为空
if not tbl.operID or not tbl.operID[1] then
SL:Print("operID数据为空")
return
end
local makeIndex = tbl.operID[1].MakeIndex
if not makeIndex then
SL:Print("MakeIndex为空")
return
end
-- 获取TRADE_DATA数据
local tradeData = SL:GetMetaValue("TRADE_DATA")
local name = ""
if tradeData and tradeData.name then
name = tradeData.name
end
-- 查找并更新或添加
local foundIndex = nil
for i, v in ipairs(t) do
if v.IDX == makeIndex then
foundIndex = i
break
end
end
if foundIndex then
-- 更新现有数据
t[foundIndex] = {
jylx = tbl.opera,
IDX = makeIndex,
name = name
}
else
-- 添加新数据
t[#t + 1] = {
jylx = tbl.opera,
IDX = makeIndex,
name = name
}
end
end
SL:RegisterLUAEvent(LUA_EVENT_BAG_ITEM_CHANGE, 'eventTag', beibao)
local function networkCB(msgID, msgData)
-- 检查是否有数据
if #t == 0 then
SL:Print("没有可发送的数据")
return
end
-- 发送第一条数据
local data = t[1]
if data and data.IDX and data.name then
SL:SendNetMsg(1000, 1, 2, 3, data.name.."#"..data.IDX)
SL:Print("发送数据:", data.name, "#", data.IDX)
-- 移除已发送的数据
table.remove(t, 1)
else
SL:Print("数据格式错误")
end
end
-- 注册正确的消息ID
SL:RegisterNetMsg(1000, networkCB)
-- 测试用:触发网络回调(实际中由服务端触发)
-- SL:ScheduleOnce(function()
-- networkCB(1000, {})
-- end, 2)
```
## 关键改进点:
1. **统一消息ID**:发送和接收使用相同的消息ID(1000)
2. **数据完整性**:确保`name`和`IDX`都存在时才发送
3. **数据管理**:只移除已发送的数据,而不是清空整个表
4. **错误处理**:添加了数据检查和错误提示
## 调试建议:
1. 添加更多打印信息来追踪数据流向
2. 检查`TRADE_DATA`的实际结构
3. 确认服务端是否正确发送了1000号消息
这样修改后,应该能正确获取到`IDX`值。如果还有问题,可以检查`MakeIndex`字段是否正确存在于`operID[1]`中。