Custom Functions

From Legacy Roblox Wiki
Jump to navigationJump to search

Needs merging into Functions

Custom functions are functions that will execute a block of code made by the programmer. There is are unique properties of a custom function, such as being reusable and will not execute until called. Also, functions can be given a name. Functions are often used to perform a specific task, and are common in most longer and more complex scripts.

Function rules

  • Function names cannot have any spaces in them.
  • Function names can have uppercase and lowercase letters in them
  • The 'variables' are commonly known as arguments. Arguments are not mandatory, but if there are none, you still need the '()'
  • All functions are ended simply by using the 'end' statement.
  • The word 'function' must be spelled as it is (all lowercase letters).
  • When you define a argument in a function, it can only be used in a function. This is called a local variable.

Defining a function

To define a function, you must follow this basic syntax:

function ''functionname''() --the function name can be named anything
   --any piece of code you want
end --this tells the script that the function ends here, and you can continue with more code

Now, you will see a simple function that prints 'Hello, world!'.

Example
function helloworld()
   print('Hello, world!')
end


Although this function has no syntax errors, but as I said before, a function has a property that will not execute until it is called.

Calling a function

This is the basic syntax of calling a custom function.

''functionname''() --that's all!

So now with the same function as last time, let's call it!

Example
--this is the previous function..
function helloworld()
   print('Hello, world!')
end

helloworld() --and now we execute it!

Output:
Hello, world


Using arguments

Like we noted before, functions can have arguments in them. This is the syntax of how you would define and call the function.

Example
function helloworld(x, y) --this is where the arguments go
   print(x, y)
end

helloworld('Hello', 'world!) --when you call it, you simply define the arguments respectively!


Custom functions in scripts

Functions can have an unlimited amount of code.

Using functions is very common in intermediate to advanced scripts, because not everything happens right when the script begins executing (when the server starts, which is when the first player enters). Functions are commonly used with events, as well. In RBX.lua, there are some pre-made functions. You can find these built-in functions here:

Built-in Functions