Need help with ModuleScript functions syntax

I have a ModuleScript:

local module = {}

return module

I know some things like:

function module.functionName(parameter1, parameter2, parameter3)
  -- Some code here
end

function module:functionName(parameter1, parameter2, parameter3)
  -- Some code here
end

function module.functionName(parameter1: string, parameter2: number, parameter3: boolean)
  -- Some code here
end

function module:functionName(parameter1: string, parameter2: number, parameter3: boolean)
  -- Some code here
end

Some things I don’t understand:

function module.functionName(parameter1: string, parameter2: number, parameter3: boolean)
  print(parameter1) -- Make this run only if parameter1 has been passed
end

-- or

function module.functionName(parameter1: string, ...)
  -- How can I print the first element of ..., then the second and so on?
end

How can I see if a parameter has been passed or get a specific element of … by it’s index?

Hello!

When a value isn’t passed to a function, it will automatically become nil. Something can be checked to be nil by using:

if parameter1 then
    -- parameter1 is passed and thereby, not nil!
end

or when you want a default, use the or comparator like this:

local value = parameter1 or "Parameter1 is nil!"

You can demonstrate that a parameter can be nil by putting a question mark behind the type like this:

parameter1: string?

the ... parameter works like a tuple, and can be converted to a table by referring it directly, like this:

local list = {...} -- same as table.pack(...)
local value = list[1] -- same as table.pack(...)[1]; {...}[1] seems to error

Hope I could help!

1 Like

Thank you so much! Also, what does the ? do? I understand that it can demonstrate that a parameter can be nil, but how can I “practically” use it, in a code for example?

As an example, your function could look like this:

function module.functionName(parameter1: string?, parameter2: number?, parameter3: boolean?)
  -- Some code here
end

When the Type Checker is activated, it would ignore when those parameters are not passed, and would warn you if a property or function return is marked as “can be nil”.

This can be useful as a reminder that something should be checked for if it is existing, but it will currently also warn if something is marked with a ?, but logically would never be nil, like .Parent, where the only case where it would be nil is when a service is used.

Hope I could help further!

1 Like

So it basically makes a parameter optional?

Exactly! A practical example would be a function, where you want something to print a specific amount of time, but default to a single time when not stated. This could look like this:

function printer(message: string, amount: number?)
    for i = 1, (amount or 1) do
        print(message)
    end
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.