How to do type casting?

local Island = {}

type IslandData = {
	Name: string,
	Model: Model,
	Owner: Player?,
	Free: boolean,
}

Island.__index = Island

function Island.New(model : Model)
	local self = setmetatable({}, Island) :: typeof(Island) & IslandData
	self.Name = model.Name
	self.Model = model
	self.Owner = nil
	self.Free = true
	
	self:SetFree()
	
	return self
end

function Island:SetOwner(player : Player)
	self.Owner = player
	self.Free = false
end

function Island:SetFree()
	self.Owner = nil
	self.Free = true
end

return Island

how can i get it so it auto suggest me the values for self?

1 Like

I mean, maybe something like this? I changed some variable names to camel-case, as its more native to lua in general. I also added the constructor and the methods inside the actual type, so it should use the autocomplete.

Let me know if there is any issues:

local island = {}

type islandData = {
	name: string,
	model: Model,
	owner: Player?,
	free: boolean,
	
	setFree: (self : islandData) -> (),
	setOwner: (self : islandData, player : Player) -> (),
}

island.__index = island

function island.new(model : Model) : islandData
	local self = setmetatable({}, island) :: islandData
	self.name = model.Name
	self.model = model
	self.owner = nil
	self.free = true

	self:setFree()

	return self
end

function island:setOwner(player : Player) : ()
	self.Owner = player
	self.Free = false
end

function island:setFree() : ()
	self.Owner = nil
	self.Free = true
end

return island

Though yours should work as intended, I tested it out, and it gave me the methods and the properties.

1 Like

This is what I usually do for classes so you do not have to manually type out the function types.

local Island = {}
Island.__index = Island

type self = {
	owner: Player?,
	free: boolean,
	model: Model,
	name: string
}
type Island = typeof(setmetatable({} :: self, Island))

function Island.new(): Island
	local self = setmetatable({} :: self, Island)
	
	-- U can set all the needed properties
	
	return self
end

function Island.setOwner(self: Island, player: Player)
    -- Notice how I used Island.setOwner and not Island:setOwner? This is important.
	-- You will have autocomplete here.
	-- When using .functionName, make sure to pass self as the first argument always
end
-- Now u can do something like this
-- local createdIsland = Island.new()
-- createdIsland:setOwner(...)

return Island
1 Like

alr this works. (30 chaarss322)

1 Like

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