Paying bits for a script teacher
#13
Being able to change things with scripts is nice, but it's only half the fun of scripting. The second, somewhat more important half is changing things dynamically, with functions, events, and loops. I'll start with the most important.

Functions have two major uses: running the same bit of code multiple times, and running a bit of code at some other time than right at the first time the script is run.

Like variables, you need to give your functions a name. However, they're a bit more complicated to define.

A basic function will look something like this:

[lua]
function namehere()
--code
end
[/lua]

Here's an example of using a function to do something:

[lua]
local circle = create("Circle")
circle.Parent = game.World
circle.Position = Vec2D(50, 50)

function red()
circle.Color = Color(255, 0, 0)
end

function green()
circle.Color = Color(0, 255, 0)
end

function blue()
circle.Color = Color(0, 0, 255)
end

red()
sleep(2) --this important little function tells the script to pause X seconds before continuing; in this case, 2
green()
sleep(2)
blue()
[/lua]

Notice how similar the three functions are? We can make things more efficient by using something called "parameters". These are extra variables you put between the parenthesis.

[lua]
local circle = create("Circle")
circle.Parent = game.World
circle.Position = Vec2D(50, 50)
local box = create("Box")
box.Parent = game.World
box.Position = Vec2D(55, 55)

function colorize(part, thecolor) --"part" and "thecolor" are our parameters
part.Color = thecolor
end

colorize(box, Color(255, 0, 0))
--variable "box" gets sent to the function as parameter "part",
--while "Color(255, 0, 0)" gets sent to the function as parameter "thecolor"
colorize(circle, Color(100, 100, 100))
[/lua]
Reply


Messages In This Thread
Paying bits for a script teacher - by Invader - 09-04-2012, 02:15 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)