.__index showing up

When accessing a new class that has been created you get the methods and whatnot.
The problem I have is that when im accessing something it also shows “.__index”
Example:

local class = {}
class.__index = class

function class.new()
 local self = setmetatable({}, class)

return self
end

when accessing it will show this:

require(class).__index

--I want this to be hidden how do I do it?
3 Likes

Ur example is empty can u fix that

2 Likes

It auto saved sorry. What about now?

1 Like

Your life would probably be easier if you worked around it.

Why is it important that you have to hide .__index anyways?

1 Like

You could use a table local to the ModuleScript your class is in to store all members specific to the instance of the class (the table returned from the .new function):

local Class = {}
local ClassInstance = {}
ClassInstance.__index = ClassInstance

function Class.new()
   return setmetatable({}, ClassInstance)
end

function Class.SomeFunc()

end

function ClassInstance:SomeMethod()

end

return Class

This additionally has the effect that you can separate visibility of class functions (like Class.SomeFunc) from instance methods (like ClassInstance:SomeMethod).

The perspective from a script requiring the module shown above would look like this:

local Class = require(Path.To.Class)

--You have access to the `new` and `SomeFunc` function but not the `SomeMethod`
local myClassInstance = Class.new()
--From the `myClassInstance` variable you can access the `SomeMethod` function
--Although the `__index` does still show up under autocomplete in studio
myClassInstance:SomeMethod()


3 Likes
local class = {}
class.interface = {}
class.schema = {}
class.metatable = {__index = class.schema}

function class.interface.new()
    local self = setmetatable({}, class.metatable)
    return self
end
function class.schema:foo()

end
return class.interface
1 Like

Why are there 4 tables in this example instead of two?

1 Like

The class itself is obviously the class.

The interface is the main class interface, usually constructors or management.

The schema is the interfaces methods.

The metatable is the index being set to the schema.

1 Like

No I mean whey are there four tables instead of the typical:

Car = {}
mCar = {}
mCar.__index = mCar

function Car.new()
    local car = {}
    setmetatable(car, mCar)

    return car
end

function mCar.Drive()
...

The reasons are listed in the post I link, but in general:

  • It makes autocomplete not list .__index and static methods on class objects
  • You can seperate out static methods from object methods

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