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

How do function parameters work?

Asked by 7 years ago

I'm still learning how to script and stuff so I don't really know much about everything. I'm really confused on parameters and how they work. Can someone please explain the various uses and give me some examples? Thanks!

2 answers

Log in to vote
1
Answered by
RayCurse 1518 Moderation Voter
7 years ago
Edited 7 years ago

In order to explain functions and their usage, we need to go on to a more abstract level first. Think of a function as a machine. You can give the machine a certain set of input and it will spit out some output. Let's say we have a function called foo(). We can give this function some input by doing foo(5 , 4). Here, we gave the foo function the numbers 5 and 4. How do we get the output of this function? In order to get the output we can do output = foo(5 , 4). In this case, the output variable would represent the output. This foo() function can be implemented in Lua like this:

function foo (x , y)
    --Do something with the input x and input y
    local sum = x + y
    --Return the output
    return sum
end

local output = foo(5 , 4) --This changes the x variable to 5 and the y variable to 4 inside the function

print(output) --This prints out 9
0
Thanks a lot! This really helped my understanding of functions! codytron3234 10 — 7y
Ad
Log in to vote
0
Answered by 7 years ago

I'll try to explain this the best I can.

Parameters are used to pass data to the function which then can be used inside the function's scope. You can then read the data by using it's name (identifier) or maybe even assign a new value to that data with the assignment operator (=). It's very useful to create functions so you don't duplicate code later and instead you could just call the function again! Parameters can be used like this, for example:

local firstNumber = 5
local secondNumber = 10

-- Heres where you can use parameters to pass data to the function
local function printAddedNumbers (x, y)
    local totalValue = x + y

    print (x.." + "..y.." = "..totalValue)
end
0
Thanks! codytron3234 10 — 7y

Answer this question