Lua OOP Object Parameters

Is there a way to specify parameters as a certain class or is that not possible with Lua objects?

1 Like

Do you mean something like this?

function Object.method(parameter: <Object>)

If so, yes, you would just need to specify or grab the type information for the object:

type ObjectType = { -- Example type definition
   Index: "luau"
}

function Object.method(arg: ObjectType) -- specify the type in the parameters
   --...
end

Likewise, you can also do this for Roblox Instances:

function Object.method(parameter: BasePart) -- Expects a BasePart to be passed
1 Like

will these persist through separate scripts?

Yes, but for types to be used in multiple scripts, you’d have to use ModuleScripts and the export keyword:

-- In a ModuleScript
export type ObjectType = { -- Exports tells the ModuleScript that this can be used both in the script and in another script
   Index: "Luau"
}

return nil -- You don't need to return anything in the ModuleScript to access the types
-- In a regular script
local types = require(ModuleScript)

local function foo(a: types.ObjectType) -- Access the type by doing ModuleScript.Type
   --...
end
2 Likes

Is it best practice to keep all custom types in a separate module script? Ive seen some people do so with their own modules scripts so I was wondering if that was the best practice.

(edit: Does it work in other module scripts or only in normal scripts?)

Personally, I do so. If I’m going to use a specific type in many different scripts, I usually make a ModuleScript for that specific type (and any others if needed)

It also works in other Modules

2 Likes

I think it depends on the use case, if it’s a type that’s only but frequently used in a single script, I would just define it in the script itself. Using modules to define types is for data that are literally used everywhere. This also applies to inherited types;

--a module
export type Thing = {a: number, b: () -> ()}
--a script
local module = require(workspace.module)
type betterThing = module.Thing & {c: () -> ()} --the "c" attribute is exclusive to this script
1 Like

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