Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call functions in other script files in Roblox

Tags:

lua

roblox

I have a script file embedded in the Workspace that contains functions. I would like call these functions from script files embedded in child objects of the Workspace. I don't want to have to copy and paste these functions into multiple script files. I figured the object oriented approach would be best if its possible.

like image 591
Slim Avatar asked Jun 28 '09 19:06

Slim


People also ask

How do you call a function from another script in Lua?

The API protocol to call a function is simple: First, you push the function to be called; second, you push the arguments to the call; then you use lua_pcall to do the actual call; finally, you pop the results from the stack.

How do you call a function on Roblox?

To call a function, type its name followed by parentheses. You can define a variable to accept the return value or use the return value in place of a variable.

How do you put a function in a module script Roblox?

Adding to Module Scripts To add a function or variable to the module which can be used in another script, type the module table's name, followed by a dot, and the name of the function or variable, like in TestModule. myVariable.


2 Answers

An alternative to _G is to use the also globally avaliable table, shared. Shared is used the same way _G is, but you must specify "shared" before the variable identifier, unlike _G, where you can merely write the name of the variable without the _G (not anymore in ROBLOX). Shared is used in the following context:

shared["variablename"] = value

Just like in the global stack, _G. Example usage of shared:

Script 1

shared["rprint"] = function(array) for i,v in pairs(array) do print(i, v) end end

Script 2

repeat wait() until shared["rprint"]
shared.rprint({"Hello, ", "How", " are", " you?"})

The output of this script would be "Hello, How are you?"

like image 63
blacksmithgu Avatar answered Sep 28 '22 09:09

blacksmithgu


The simplest way would be to use _G or shared.

In one script,

_G.myFunction = function(Arguments)

-- blah

end

In another script, you would use this code.

repeat wait() until _G.myFunction ~= nil

_G.myFunction()

This would also work with the global table shared, instead of _G.

like image 40
user809559 Avatar answered Sep 28 '22 11:09

user809559