Don't know how to put colon

Because of Roblox for some reason disliking OOP, I’ve made my own createClass function, but for that to work I have to define functions like method = function() end, and that means that I can’t define them with a colon, which means that I can’t use the self keyword. Are there any way to tell the compiler or whatever that I want to use it with a colon so that I can actually use the self keyword?

2 Likes

U mean function v.new() end and function v:method() end ?

3 Likes

If you are defining functions inside of table, then simply name first parameter of the function self. Maybe not something you want but that’s the only one way

local someTable = {
    someMethod = function(self)

    end
}
1 Like

Can you provide your code structure that you are using? There are many ways to use OOP and not have this issue, so without seeing how you are trying to approach it, an answer provided is basically a blind pitch hoping it’s hitting whatever the target actually looks like

The colon just assigns the self keyword automatically, by no means do you need it in order to use self. Just assign self manually.

local t = {}
t.__index = t

t.new = function(name)
	return setmetatable({Name = name}, t)
end

t.getName = function(self) -- same as: function t:getName()
	return self.Name
end

local thing = t.new("test")
print(thing:getName()) -- test
2 Likes

Sure, sorry for a late reply, but devforums was pretty slow for me.

But yeah I’m just using it like

local Class = require(game.ReplicatedStorage.ClassBase)

return Class.newClass{
	new = function()
		print("constructor")
	end,
	
	method = function()
		print("method")
	end,
}

I know, but I would rather not asign it manually, but I understand that this may be the only solution…

Yeah, but I can’t do that since I do like variable = function() end and not function something() end

I’d get rid of that habit if I were you. Most languages have the function keyword before the name anyways so it’s better to get used to it if you plan on changing engines in the future.

I know, but I can’t do that in my instance since I am defining the functions inside of the newClass() function

If I were you I’d just rewrite all of the classes.

Why? I really want to use this function. I hate how I have to do all that local self = setmetatable({}, class} and all that. This is much better and closer to actual OOP from other languages.

Might be closer, but it just doesn’t work like this in luau and it’s better to do it the most commonly used way.

At the end of the day the game isn’t gonna change because of this. Just choose the method that you’re comfortable with and stick with it.

1 Like