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

Whats the point of function in local function?

Asked by 2 years ago

So I'm a beginner scripter, and I don't understand functions? You could just do local the = 2 instead of local function = 2 so why use function?

2 answers

Log in to vote
1
Answered by
Mineloxer 187
2 years ago

Functions are named blocks of code that can be executed whenever called. They are different from variables, as variables are named values of data. For example:

local variableName = 3
local name = "Jester"

These are variables, you specify a name and assign a value to them. They could be numbers, strings (collection of characters, refer to second variable in the previous example), etc.

For functions, they work differently. Take the following as an example:

-- Function's name is "add" and takes two parameters, "x" and "y" which are both numbers.
local function add(x, y)


    -- Add x and y and assign the sum to the variable named "sum"
    local sum = x + y



    -- Return the sum
    return sum
end

--  Whatever the function returns as the result is assigned into the variable "result"
local result = add(1, 2)

-- This prints 3, as the value returned from add(1 ,2) is 3
print(result)

For functions you specify a name, parameters, and then define the instructions inside. In this example, the function add() can be called anytime with 2 numbers as arguments, and it will return the sum. Note: You dont always need to specify any parameters for functions. Refer to the documentation at the end of this answer.

In the examples you gave, they're both variables. Except, one of them is named "function". This isn't actually a function, just a variable named so.

As per variable-naming conventions, you don't use keywords as variables names. Keywords are any words reserved by the programming language you're using or other libraries/modules. "function" is a keyword, as it's used for defining functions, so you don't want to use that. Other examples of keywords in Lua: "local", "if", "else", "for", "do", and more.

To learn more about Lua (the programming language that Roblox uses for scripts), you can read the documentation here:

https://www.lua.org/pil/1.html

Here is the documentation for variables:

https://www.lua.org/pil/1.2.html

https://www.lua.org/pil/4.2.html

And here is the documentation related to functions in Lua:

https://www.lua.org/pil/5.html

Ad
Log in to vote
0
Answered by
Catr899 12
2 years ago

Functions are used for being able to be used multiple times at any time, Functions are sets of instructions that can be used multiple times in a script. Once defined, a function can be executed through a command or triggered through an event. Such as

local function addNumbers() -- Function body print("Function called!") end

and then you could say

wait(3) addNumbers()

to run that function

Answer this question