Having a shared function (shared.function)

Hey! Before I begin I want to clarify; I’m not interested in whether using shared is good design or not; I just want to learn what I’m doing wrong in this context and why.

I am unsure of how to write a function that is accessible through all scripts with shared. I thought I could write a function, and then have it accessed through shared. For example;

Script where shared is defined;

local function test(name)
     print(name)
end
shared.testFunction = test

Another script;

testFunction = shared.testFunction
testFunction("MediocreMushroom") -- attempt to call nil value
shared.testFunction("MediocreMushroom") -- attempt to call nil value

I have tried a few different things; in the first script I’ve tried directly doing shared.testFunc(name) and then writing the body; I have also tried switching around how I connect the variables. I also tried comparing to what I’ve seen done with _G on other posts but it didn’t work and most posts only spoke about _G and not shared.

Thanks for any insight!

ModuleScripts were made for essentially this purpose. You should think about using those instead of shared or _G to share things between scripts.

1 Like

Again, I appreciate this but I very explicitly stated I was not interested in this answer but rather a solution to the shared function. Do you have any insight on that?

What’s the need to use shared here? Is it just to mess around with it and figure it out? Because it should be the same thing as _G. They serve the same purpose.

To point out _G variables (shared as well as they work the same way) have performance repercussions in your game, as @MrLonely1221 kindly mentioned in their post, use Module Scripts.

For anyone in the future wondering, here is the format I used to get this to work. Not sure why I was having initial issues;

Script 1:

shared.testFunction = function(variable1, variable2)
print(variable1 .. variable2)
end

Script2:

local newString = shared.testFunction("Hello", "Goodbye")
print(newString) -- HelloGoodbye

You can add a line

 repeat task.wait() until shared.testFunction 

In the beginning of script 2. That should ensure that the data is loaded.

Declaring the function in a local variables takes a few milliseconds. So the script 2 tries to read the value of shared.testFunction before it is written, thus you get nil.