UevKF8zjRV_WEtpJsXhr
We use cookies on this site to enhance your user experience

Using return In a Function

return will stop a function and take the script back to the line where the function was originally called. If there is something after the keyword return, that information is sent back through the function.

In this case, return brings back the value of currentIndex and stores it in the original variable where findValue() was called.


Use a Found Value

If a value was found using the find function, then it can be removed. So the script doesn’t try to remove a value that doesn’t exist and create an error, check if a value was found with an if statement.

  1. To check if a value is inside indexToRemove, use an if statement. In the statement, remove the found value by typing table.remove(playerItems, indexToRemove).
  1. Print out the array using the code below.
  1. Run the project and check that the first "Bread" was removed from the array, but the second one is still there. To further test the script, try removing other values by changing the second parameter in findValue().

Before removing the first "Bread"

After removing

Because this function was called once, it will only remove the first "Bread" it finds. The next section will cover how to find and remove all instances of a function.

While the function findValue() works with string and number values, be careful with the specific values you compare. For example, if you had a player, you’d need to check their Name value using the comparison:

player.Name == "playerNameToCheck" 

Find and Remove All of a Value

While the previous code could only remove the first instance of value found, this code snippet will find and remove all occurrences of from an array.

Remember, removing items causes later indexes to shift. Instead of starting at the beginning of the array, start at the end to avoid accidentally skipping values. By starting at the last index, you won’t change the indexes of the values before it.

  1. Use an array named playerItems with at least four values and a set of duplicates.
  1. To go through the array, create a for loop that goes backwards through playerItems, starting at #playerItems, ending at 1, and incrementing by -1.
  1. In the loop, remove a "Bread" value with an if statement that checks if the value inside playerItems[index] is equal to "Bread".
If found, use table.Remove(playerItems, index) to remove that value.
  1. Use the code below to add a second for loop that prints the array.
  1. Run the script and check that all valued named "Bread" are removed.

Finished Project Sample

Project File

The following project includes all scripts in this tutorial. Download here.

Note, all scripts are in ServerScriptService and disabled. To use a script, in its properties, uncheck the Disabled field and run Studio.