What's the difference from function and local function and `:` and `.` for a custom function?

Hello, I’m making a module script for my new game that is supposed to be a re-imagined game from cool math games.

I’m wondering for this custom function in my module script what the differences are from : and . and also local function and function

1 Like

The difference is the scope, that is where it can be used.

2 Likes

Local function allows it to be garbage collected (if it’s in another function, it’ll get deleted.)
Also . Is used for referring to parts or properties:

workspace.Part.Material = Enum.Material.Fabric

While : is a bit weirder to explain, but it ALWAYS has () afterwards. It’s usually better to use :
Examples:

game.Players.LocalPlayer.Humanoid:TakeDamage(100) --better than health -= 100. It didn't work with my death script. :Take damage did though.
game.Workspace.Sound:Play() --will start from the beginning/last time the time position was changed by a script. :Stop() resets kt to 0

And so on.
Also here’s the most important one: :Connect() because without it, you can’t connect functions to an event.

1 Like

local creates the function in the current scope. Example:

do
  function foo() print("Foo") end
  local function bar() print("Bar") end
end

foo() -- Works fine
bar() -- Doesn't work, because bar only exists in the "do" block

In general, try to use local, because it’s a little more optimized.

As for: vs ., when creating functions in objects, : has the self parameter defined. self is the current object. It’s mostly used in OOP. Example:

-- Create a car class with a speed variable
local Car = {}
Car.__index = Car

function Car.new(speed)
  local newCar = {}
  newCar.speed = speed

  -- Basically copies all the Car functions into the newCar variable
  return setmetatable(newCar, Car)
end

function Car:drive()
  local distance = 10 * self.speed -- self is defined as the car
  -- Move car by distance...
end

function Car.drive2()
  -- This doesn't work.
  -- We would need to add a parameter called "self" to this function
  -- Then, we would need to call the function such as myCar.drive2(myCar), which is stupid
  local distance = 10 * self.speed
end

local myCar = Car.new(6)
myCar:drive() -- Works
7 Likes