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
I know the solution has already been given, but I’m sending this for a little clarification.
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).
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;
};