Roblox(Lua)如何为函数创建变量及对应语法报错问题咨询
报错根因
你遇到的是Lua语法规则不兼容导致的解析错误:
Lua提供两种合法的函数声明方式,你的写法混淆了两种规则:
- 方式1:将匿名函数赋值给变量,语法为
local 变量名 = function() 函数逻辑 end,function关键字后直接跟参数括号,不允许额外加函数名,你额外加的onMouseClick属于无效语法,解析器预期读取(时读到了标识符onMouseClick,因此抛出对应报错。 - 方式2:直接声明命名函数,语法为
local function 函数名() 函数逻辑 end,不需要用赋值写法。
另外你现有代码还存在一处逻辑错误:barlight = workspace.barlight:GetChildren()获取到的是实例数组,数组本身没有Transparency属性,直接赋值会触发运行时错误,需要遍历数组内的每个子实例单独设置属性。
修正后可运行的完整代码
local colorwheel = script.Parent local clickdetector = colorwheel.ClickDetector local barlightParts = workspace.barlight:GetChildren() -- 右键关灯逻辑 local rightmouse = function() print("turned the lights off") for _, part in ipairs(barlightParts) do if part:IsA("BasePart") then -- 仅对零件类型对象设置透明度,避免触发无关报错 part.Transparency = 1 end end end -- 左键开灯逻辑 local leftmouse = function() print("turned the lights on") for _, part in ipairs(barlightParts) do if part:IsA("BasePart") then part.Transparency = 0 end end end clickdetector.RightMouseClick:Connect(rightmouse) clickdetector.MouseClick:Connect(leftmouse)
内容的提问来源于stack exchange,提问作者CoderCode
相关产品推荐
相关产品推荐

