How do I prevent a function in a table being called with a period

Basically I want to make a function that can only be called with colons.

But this function can be called from colons and periods. How do I prevent this from happening?

Code just incase you need it but it’s pretty much empty.

local _T = {}


function _T:GetInfo()

return print("Test")	
end


return _T

This is not possible, but you can make it error by detecting if it has self.

Simply add a variable in the first parameter of the getInfo function. If self exists, then it means it was called with the colon operator, and you can error. Otherwise, it was called with the dot operator, and you can continue.

2 Likes

Hello.

You don’t. Simple as that.

Tables are structures that allow indexing, i.e. the dot operator when accessing data inside them. The colon is also a way of accessing indices that are functions, but the big difference is that the colon operator sends the table itself as an argument. Lua does that to make OOP easier for the user.

local Object = {}

function Object:DoSomething(arg)
    print(arg)
end

return Object

Doing Object.DoSomething() will print nil, but doing Object:DoSomething() will print the Object table.

Note that doing Object.DoSomething(Object) is the same as Object:DoSomething().

Best regards,
Octonions

1 Like

In your current set up you can just do…

local _T = {}

function _T:GetInfo()
    assert(self == _T, "Cannot call GetInfo without a semicolon.")

    print("Test.")
end

return _T

But for more involved OOP patterns you’ll likely do metatable checking.

1 Like

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