Question about custom types

Tried searching, couldnt find anything sadly, anyhow to the point.

My question involves well custom types, So, lets say I have a custom type defined in a module, and with said module I can create a new variable that is assigned to that type.

Now in another script, that variable gets passed to it, ofc at this point it doesnt know what it is, is there anyway I can pass the custom type, without creating a new thing assigned to that custom type

I don’t understand what you mean

Ok, example time!

-- // Types //
type Owner = {UserId:number}

local module = {}

module.NewOwner = function(Player:Player)
	local Owner:Owner = {}
	
	if Player then
		Owner.UserId = Player.UserId
	end
	
	return Owner
end

return module

This module creates what I call an owner, again just an example.

Now after I return the Owner, I send it via a remote event

local Owner = module.NewOwner(PlrHere)

RemoteEvent:FireServer(Owner)

Now on the server, it gets the owner, ofc the script has no idea what it is:

RemoteEvent.OnServerEvent:Connect(function(player, Owner)
    -- This script doesnt know what an "Owner" is
end)

So how can I assign the type of the passed value Owner, as well the type, Owner.

1 Like

Basically the code should now be

export type Person = {
	FirstName: string,
	LastName: string,
	Age: number
}

local Person = {}

function Person.GetFullName(person: Person)
	return `{person.FirstName} {person.LastName}`
end

return Person
local Modle = require(game.ReplicatedStorage.ModuleScript)

local person: Modle.Person = {
	FirstName = 'Max',
	LastName = 'Test',
	Age = 20,
}

print("Person", person)
print(Modle.GetFullName(person))
2 Likes

Ahh so the trick I take from the video is use export, tried it out and it seems it works, thanks!

Oh also on the subject, is there a way to tell if a value in a custom type is changed? I take it I need metatables but Idk what I’m doing to be honest

You could use Signals.

I realize this has been solved, but the official Luau page also has a section on typing with OOP here.

I should point out that sleitnick’s solution given by @SchmeckoGecko has two issues: a) it prevents you from using the shorthand self function call (so instead of Class.Method1(Object) you have Class:Method1() and b) you lose access to rather useful methods like __index, which only exist in the context of metatables. EDIT: also, you expose methods this way and are forced to pass entire tables which is quite network-hungry

There is currently no way to listen for when a pure variable changes. You’d either have to a) use context to determine when the value changes or b) listen by means of a loop.

1 Like

I figured it out, with the use of metatables! Somehow I figured it out!

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