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

Roblox Lua开发排行榜报错:attempt to index a nil value (global 'game')

Roblox排行榜系统问题解决指南

关于Lua演示环境的报错

普通Lua环境没有Roblox引擎提供的game全局对象,这类代码只能在Roblox Studio内的服务器脚本中测试,外部Lua环境无法运行Roblox专属API。


三段代码的问题分析与修正

第一段代码

错误点:

  • instance.new 必须大写为 Instance.new,Roblox API严格区分大小写
  • Instance.new 调用格式错误,不能把父对象写在第一个参数里,需先创建实例再设置Parent属性
  • 变量大小写不一致:Points与points、XP与xp是不同变量,Lua对大小写敏感

修正后代码:

game.Players.PlayerAdded:Connect(function(player)
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player

    local Points = Instance.new("IntValue")
    Points.Name = "Points"
    Points.Parent = leaderstats

    local XP = Instance.new("IntValue")
    XP.Name = "XP"
    XP.Parent = leaderstats
end)

第二段代码

这段代码逻辑本身是正确的,游戏内无效果大概率是脚本位置错误:

  • 必须将脚本放在ServerScriptService或Workspace中,且必须是服务器脚本(Server Script),不能用本地脚本(LocalScript)。PlayerAdded事件只能在服务器端触发,本地脚本无法监听全局玩家加入事件。

第三段代码

错误点:

  • gold.value 需大写为 gold.Value,Roblox对象属性严格区分大小写
  • if player then 判断多余,PlayerAdded回调的player参数必然是有效的玩家对象

修正后代码:

local players = game:GetService('Players')

players.PlayerAdded:Connect(function(player)
    local folder = Instance.new('Folder')
    folder.Name = "leaderstats"
    folder.Parent = player
    
    local gold = Instance.new('IntValue')
    gold.Name = "Gold"
    gold.Parent = folder
    gold.Value = 125 -- 修正属性大小写
end)

通用注意事项

  • 服务器逻辑必须用Server Script,放在ServerScriptService或Workspace;客户端逻辑用LocalScript,放在玩家相关容器(如PlayerGui)
  • Roblox的类名、属性名、方法名全部严格区分大小写,必须与官方文档一致
  • 所有Roblox专属代码只能在Roblox Studio内测试,外部Lua环境不支持Roblox的全局对象与API

内容的提问来源于stack exchange,提问作者Atomic Studios

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:35:26