Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

What can you do with Custom Functions?

Asked by
woodengop 1134 Moderation Voter
9 years ago

I'd like to know if you can create your own Function besides the ones related to Mouse,Keys, Part Functions(Like the Touched event). I've seen Other functions like:

function PrintFunction()--One question: What do you do with the ()?
    print("hi")
end
PrintFunction()--Can you add Other things inside this?

4 answers

Log in to vote
2
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

You're incorrectly conflating events and functions.

Events, such as Touched, are connected to functions via the connect method (which is actually also a function!)

Functions are, very simply, "blocked off" sections of code.

The parentheses have two meanings, depending on if you're defining or calling the function:

--Defining
function FuncName(param1, param2)
    print(param1)
    print(param2)
end

--Calling
FuncName("hooplah", 12)

param1 and param2 are the parameters of the function. They are filled by passed-in arguments "hooplah" and 12 on line 8. You can have a very large (on the order of thousands) of parameters before Lua will start yelling at you, but having more than a handful is a good sign you're doing too much in a single function.


You can write functions for any bit of code, and they are especially useful for otherwise repetitive code. Another usage is "extracting" code in a bite-sized piece, either to make your code easier to read or because you can't in-line the code easily.

An example of the first case is displaying a message:

function showMessage(player, msg)
    local gui = player.PlayerGui.ScreenGui.Message
    gui.Text = msg
    gui.Visible = true
    wait(2)
    gui.Visible = false
end

--somewhere else in the code:

showMessage(game.Players.adark, "Here's an example argument!")

What makes this especially lucrative is you can make the entire message system different by just changing how this one function displays the given text, without having to touch any of the rest of the code.

An example of the second case, taking a factorial:

function factorial(n)
    --if negative or not an integer
    if n <= 0 or math.floor(n) ~= n then
        return nil
    end

    for i = n, 1, -1 do
        n = n*i
    end

    return n
end

print(factorial(5)) -- 5*4*3*2*1 = 120

The simple 3-line loop could be inlined, but what happens if you make a mistake writing it? Having the code in only one area means any error will be evident every time the function is used, instead of just one or two of the ten or more times you used the factorial inline.

This function also displays the second aspect of functions: returning values. You can return any number of values, using the , operator (a comma) to separate them. factorial returns only one, but here's an example that returns multiple:

function returnMultiple()
    return "alpha", "omega", 42
end

a, b, c = returnMultiple()

print(a)
print(b)
print(c)

What's useful but not always practical is chaining together multiple returns with multiple arguments:

function printThreeThings(a, b, c)
    print(a)
    print(b)
    print(c)
end

function generateThreeNumbers()
    return math.random(), math.random(), 7
end

printThreeThings(generateThreeNumbers())

Functions are considered first-class values, meaning they are the same as any other kind of data. What this means to you is that you can return functions as well!

function printBobFunction()
    return function()
            print("bob")
        end
end

printBobFunction()() -- The first set of parentheses call `printBobFunction`. The second call the function it returns!

The odd-looking function in there is called an anonymous function. You may be familiar with them in a slightly different case:

script.Parent.Touched:connect(function(hit)
    print(hit)
end)
0
This has helped me so much, its more than Knowledge...it's Truth. woodengop 1134 — 9y
Ad
Log in to vote
2
Answered by
Redbullusa 1580 Moderation Voter
9 years ago
function PrintFunction(message)
    print(message)
end
PrintFunction("hi")

What did I just do here? I've sent a string in a function, and it prints out whatever that string displays. This is called passing arguments.

What I just demonstrated is using parameters and arguments.

Parameter - A "room" where an argument can be "stored" into.

Argument - Provided information that can be used in a function.

The definitions for these terms are rough, because I'm terrible with definitions; but once you experience with them, you'll understand it. You may refer to the link provided from "passing arguments".

Functions that are coded to be like this tend to be used generally, such as a calculation using a formula.

function Example( --[[ Parameter ]] )
    print( --[[ Argument given from the parameter, or the PASSED ARGUMENT ]] )
end

Example( --[[ Argument ]] )

EXAMPLES

function Multiply(x, y)
    local Answer = x * y
    print(Answer)
end

Multiply(7, 3)
--[[
OUTPUT

21
]]
function PythagoreanTheorem(a, b)
    local Answer = math.sqrt(math.pow(a, 2) + math.pow(b, 2))
    print(Answer)
end

PythagoreanTheorem(3, 4)
--[[
OUTPUT

5
]]
Log in to vote
1
Answered by
attapi0 20
9 years ago

You can use functions to create pieces of code that take in inputs and output something.

Lets say I have a function drawText(text, time)

Lets say draw text creates a screenGui, creates a text label, makes it say whatever you put in the the text variable, and deletes itself after the time variable is over.

Later on, I can call drawText("Yo momma", 2) and it would display "Yo momma" on screen for two seconds. Of course, you'd have to write in this behavior though.

Log in to vote
-1
Answered by 9 years ago

just to add to the other answers, most people use this method when creating an event:-

Method1:-

script.Parent.Touched:connect(function(hit) --The function is created in the event like this
    print(hit.Name)
end)

When an event get to large or if you prefer to use this method of passing the event arguments to another function. This may help you depending upon what you care coding:-

Method2:-

function printPlr (hit)
    print(hit.Parent.Name)
end


--This keeps the event code very small, which will help keep the code readable
--If multiple events are needed they are nested in this event you are then able 
--To re-use code unlike method1
script.Parent.Touched:connect(function(hit)   printPlr(hit)  end)

Just in case you don't already know you can make a function "Global" so it is available to all scripts Click Here . I have seen some problems with it but they can be useful in some cases.

Hope this help.

0
Since you're just passing the argument on, "method 2" can be written like so: `script.Parent.Touched:connect(printPlr)`. Also, you don't "create" events, you just connect to them. adark 5487 — 9y

Answer this question