如何在 Roblox 中为函数创建变量 (Lua)

How to create a variable for a function in Roblox (Lua)

local colorwheel = script.Parent
local clickdetector = colorwheel.ClickDetector
local barlight = workspace.barlight:GetChildren()

--attempting to establish function as variable--
local rightmouse = function onMouseClick()
        print(" turned the lights off")
        barlight.Transparency = 1
end

local leftmouse = function onMouseClick()   
        print(" turned the lights on")
        barlight.Transparency = 0
end

clickdetector.RightMouseClick:connect(rightmouse)
clickdetector.MouseClick:connect(leftmouse)

我正在尝试创建一个函数,以便在单击模型“colorwheel”时更改“barlight”模型的透明 属性。我想为 onMouseClick() 函数建立两个单独的变量,这样我就可以根据单击它的鼠标按钮更改函数的行为方式。一个用来开灯,一个用来关灯。所有这些都是在服务器脚本而不是本地脚本中完成的(不确定这是否意味着什么

local rightmouse = function onMouseClick()
local leftmouse = function onMouseClick()

当我尝试使 onMouseclick() 成为一个变量时,它在单词本身的正下方有一条红色下划线,并告诉我“Workspace.barlight wheel.Script:5: Expected '(' 解析函数时,得到 'onMouseClick'" 有什么想法吗?

function onMouseClick() end定义了一个函数。它不解析为函数值。因此,您不能像

中那样将其分配给局部变量
local rightmouse = function onMouseClick()
        print(" turned the lights off")
        barlight.Transparency = 1
end

这是不正确的语法。您可以通过两种方式定义函数:

local function myFunction() end

local myFunction = function () end

所以要么

local rightmouse = function ()
        print(" turned the lights off")
        barlight.Transparency = 1
end

如果您希望函数的名称是rightmouse,或者

local function onMouseClick()
        print(" turned the lights off")
        barlight.Transparency = 1
end

如果您希望函数名称为 onMouseClick