如何在Roblox中的其他脚本文件中调用函数

Sli*_*lim 4 lua roblox

我在包含功能的工作区中嵌入了一个脚本文件。我想从嵌入在工作区的子对象中的脚本文件调用这些函数。我不想将这些功能复制并粘贴到多个脚本文件中。我认为如果可能的话,面向对象的方法将是最好的。

小智 5

_G的替代方法是使用全局可用的表shared。共享的用法与_G相同,但是您必须在变量标识符之前指定“共享”,这与_G不同,在_G中,您只能写没有_G的变量名在ROBLOX中不再可用)。共享用于以下情况:

shared["variablename"] = value
Run Code Online (Sandbox Code Playgroud)

就像在全局堆栈中一样,_G。共享的用法示例:

脚本1

shared["rprint"] = function(array) for i,v in pairs(array) do print(i, v) end end
Run Code Online (Sandbox Code Playgroud)

剧本2

repeat wait() until shared["rprint"]
shared.rprint({"Hello, ", "How", " are", " you?"})
Run Code Online (Sandbox Code Playgroud)

该脚本的输出为“你好,你好吗?”


小智 1

您可以将该函数设为全局。在一个脚本中执行以下操作:

_G.myFunction = function() print("Hello World") end
Run Code Online (Sandbox Code Playgroud)

在另一个脚本中执行以下操作:

repeat wait() until myFunction myFunction()
Run Code Online (Sandbox Code Playgroud)

通过定义一个函数为_G,您必须等待脚本执行分配该函数,然后即使不指定_G也可以调用该函数。