Scripting Book/Chapter 8

From Legacy Roblox Wiki
Jump to navigationJump to search

Now we're going to learn about pcall. This will help check our script's sources before we run them through the loadstring function.

How it works

Pcall checks that the script is error-less and won't cause the whole script to crash.

Let's begin

Previous script

code = [[ p = Instance.new("Part", game.Workspace) p.Anchored = true ]]

loadstring(code)()

Checking it with pcall

Step 1

First of all we need to start an 'if' statement,

if

Step 2

Now we need to add in the pcall function containing one argument, which will be the start of a function(), after the function we need to remove the variable name and the '[[' and ']]'s from around the source.

if pcall(function() p = Instance.new("Part"), game.Workspace) p.Anchored = true

Step 3

Now we need to end the function and close the remaining braket and add the 'then'.

 if pcall(function() p = Instance.new("Part", game.Workspace) end) then

Step 4

Next we need an 'else', just incase the source has an error in it

if pcall(function() p = Instance.new("Part", game.Workspace) p.Anchored = true end) then

else

Step 5

Finally we need to print some text in output saying it is broken, and we need an 'end' to end the 'if' statement.

if pcall(function() p = Instance.new("Part", game.Workspace) p.Anchored = true end) then

else

print("The source has an error.")

end 

The finished script

Here's the finished script:

if pcall(function() p = Instance.new("Part", game.Workspace) p.Anchored = true end) then

else

print("The source has an error.")

end 

Go to previous chapter or Continue to Chapter 9