Struggling To Understand Functions

Hello! Im Currently Learning to Script, However I still cannot Understand Functions. What Can i Use These for? Just Note Im Not Asking for full Scripts, I am Just Curious To Learn The Most Effective way to learn/understand Functions. Some Solutions i have tried are using YouTube But it just wont stick with me.

They are reusable blocks of code. Study this simple example:

-- Defining a reusable block of code that can be 'called' later
-- The code within this function will not run until called
function MyFunction(input1, input2)
   print(input1 + input2)

-- Now we 'call' the function as many times as we need, sending in input1 and input2
MyFunction(5, 5) -- prints 10
MyFunction(10, 5) -- prints 15
MyFunction(10, 10) -- prints 20

I suggest looking at other code pieces or examples to see how functions are used.

You can look around the dev forum in #resources:community-resources or here in #help-and-feedback:scripting-support to find more

Like here is one I found with a usefull application with inventory.

Here is one more that is commonly used to get the mouse hit position via raycast with the newer raycasting methods.

1 Like

So in a way it helps keep code short, and not as messy as it would be without a function?

I Will Defiantly Read Through These Articles!

Exactly, and it allows you to stay organized and send different inputs to the same code.

1 Like

So for example i could write something like

function partTransparency()

partTransparency = 0.5

Would This be a working function?

You have to call a function using parenthesis.

This would work:

function SetTransparency(value)
   game.Workspace.Part.Transparency = value

SetTransparency(0.5) -- Calling the function with an input

Alright, I Believe That I Am Starting to get the hang of it Thank You for all your help!