You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Roblox Data Store V2读取返回nil 触发Attempt to index nil with Version报错求助

核心错误原因

  • LoadPlayerData 函数中,pcall 包裹的匿名函数没有返回 GetAsync 的执行结果,导致调用成功后 CurrentNumber、KeyInfo 两个变量始终为 nil,触发索引空值的报错。
  • 测试触发逻辑顺序错误:玩家进入游戏时先触发 PlayerAdded 加载数据,此时还未执行过仅在退游时触发的 SaveNumberData 逻辑,首次读取必然无数据。
  • 可选优化:当前写死了 PlayerKey = 'Player_1234',所有玩家会共享同一个存储键,正式使用可替换为 'Player_'..Player.UserId 区分不同玩家数据。

修正代码

仅需要修改 LoadPlayerData 中 pcall 的包裹逻辑即可,完整修正后的代码如下:

local DataStoreService = game:GetService('DataStoreService')
local Players = game:GetService('Players')
-- Data Stores:
-- 启用Data Stores V2
local Options = Instance.new('DataStoreOptions') 
Options:SetExperimentalFeatures({["v2"] = true})

local NumberStore:DataStore = DataStoreService:GetDataStore("PlayerNumber", "global", Options)

local SetOptions = Instance.new('DataStoreSetOptions')
SetOptions:SetMetadata({['PlayerNumberType'] = 'Int'})


local function SaveNumberData(Player:Player)
   local Number = 1
   
   local PlayerKey = 'Player_1234' -- 正式使用可改为 'Player_'..Player.UserId
   
   local Success, Errormessage = pcall(function()
       NumberStore:SetAsync(PlayerKey, Number, {Player.UserId}, SetOptions)
   end)
   
   if not Success then
       print(Errormessage)
   else
       print('数据保存成功')
   end
   
end

local function LoadPlayerData(Player:Player)
   
   local PlayerKey = 'Player_1234' -- 正式使用可改为 'Player_'..Player.UserId
   
   local Success, CurrentNumber, KeyInfo:DataStoreKeyInfo = pcall(function()
       -- 新增return返回GetAsync的执行结果
       return NumberStore:GetAsync(PlayerKey)
   end)
   
   if Success then
       print(CurrentNumber)
       if KeyInfo then -- 新增空判断避免首次无数据时报错
           print(KeyInfo.Version)
           print(KeyInfo.CreatedTime)
           print(KeyInfo.UpdatedTime)
           print(KeyInfo:GetUserIds())
           print(KeyInfo:GetMetadata())
       end
   else
       print(CurrentNumber)
   end
   
end

Players.PlayerRemoving:Connect(SaveNumberData)
Players.PlayerAdded:Connect(LoadPlayerData)

测试方法

第一次进入游戏退出后会触发保存,第二次进入游戏即可读取到已存储的数据。也可以在服务器逻辑中新增主动触发保存的测试逻辑,无需反复退出重进验证。


内容的提问来源于stack exchange,提问作者Arthur Buzas Baccan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 09:15:03