Small modulescript question

If I’m writing a modulescript should I have normal functions inside of it or is that a bad practice?

i.e

local myModule = {}
myModule.__index = myModule

function myModule.new() 

end

local function doMoreStuff()

end

function myModule:doStuff()
      doMoreStuff()
end
return myModule

Completely normal. The normal functions are called private functions. They’re not exposed.
myModule functions are exposed and they can be used

1 Like

Alright thanks. Idk why it just felt icky for some reason

1 Like

I know the solution has already been given, but I’m sending this for a little clarification.

  1. Having local functions in the class module is undoubtedly a common practice. It reduces the size of the returned table if the function doesn’t have to be part of the exposed functions. For example, Init(self) function, a function to calculate and return the closest point etc. Plus, the function can’t be accessed externally. However, this means it’s technically not part of the class (prototype in Lua).

  2. While doMoreStuff() is considered an internal/hidden function of the module, it is strictly speaking not a private member.

A private member (be it a var or a function) is a member of the class! and not exposed outside of the class itself - intended for use within the class to encapsulate the implementation details. Access from outside is restricted.

So doMoreStuff() is a standalone function that is not part of the class, though its often referred as a private function.

Vanilla Lua

Doesn’t have any built-in modifiers for this, but the naming convention is the same as in Python (underscore).

function module:_doStuff() ... end

These members are obviously not restricted, but they indicate their private nature.

Luau

With the help of type checking and a proxy table, we can successfully hide members. See this topic: My Approach for OOP in Luau.

OOP languages like C++ and Java

Typically low-level languages come with access specifiers. Declaring variables requires them to define member access. For instance, C++ has private, public and protected. Any inconsistencies raise an error during compilation.

Example:

#include <iostream>
using namespace std;

class Class {
private:
    void introverted_function() {
        cout << "Hey there, me too, but I change the world more quietly." << endl;
    };
public:
    void extroverted_function() {
        cout << "Hello! I'm very friendly, positive, outgoing any communicative!" << endl;
        introverted_function(); // Calling a private function internally.
    };
};
 
int main() {
    Class Classy;
    Classy.extroverted_function();
    //Classy.introverted_function(); // Compilation error because it's private.
    return 0;
};

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