Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Custom Method Possibilities?

So, I know you can make custom methods that effect instances like so..

function obj(o)
	return {
		Invisible = function()
			o.Transparency = 1
		end
	}
end

obj(workspace.Part):Invisible();

But is there any way that I can make a custom method to react directly off of the part instance so I could call the method like workspace.Part:Invisible() rather than obj(workspace.Part):Invisible()?

I know this question is kinda broad and vague but i'd appreciate any and all help.

2 answers

✓ Accepted answer

If you wanted to, you could wrap all ROBLOX objects that you want to use in Lua "objects" using a ModuleScript like so:

local PART = {} --name doesn't really matter here, this is just for clarity
PART.__index = PART --Allows inheritance

function PART.new()
	local newpart = {}
	setmetatable(newpart, PART)
	newpart.obj = Instance.new("Part", workspace)

	return newpart
end

function PART.Invisible(this)
	if this.obj then
		this.obj.Transparency = 1
	end
end

return PART

And in another Script...

local PART = require(game:GetService("ServerScriptService").PART)

local part = PART.new()
wait(1)
part:Invisible()

part.obj.BrickColor = BrickColor.new("Bright green")

If you didn't want to supply a reference to the Part itself (which you would do if you want to restrict access to it for whatever reason), you can define the methods in the new function itself:

local PART = {}

function PART.new()
	local newpart = {}
	local obj = Instance.new("Part", workspace)
	function newpart.Invisible()
		obj.Transparency = 1
	end
	return newpart
end

return PART

And in another Script...

local PART = require(game:GetService("ServerScriptService").PART)

local part = PART.new()
wait(1)
part:Invisible()

part.obj.BrickColor = BrickColor.new("Bright green") --ERROR

As of now Roblox Studio doesn't allow you to manually create custom methods for instances, variables, etc... But in the near future, Roblox might be planning to implement this feature thus allowing more efficient scripts!!!

This discussion is preserved as it was. New answers, comments, and votes are closed.