How to set a function up with a module

Yeah, it’s not entirely necessary, but it’s recommended. The __index metamethod becomes more relevant in OOP.

This will do that…

--Script
local module = require(script.ModuleScript)

module.functionName()
print(module.newVal)
--Module script
local module = {}

function module.functionName(newVal)
	return newVal
end

while true do task.wait(0.1)
	print(module.functionName("hello"))
end

return module

It is returning the newVal as normal. But then hitting a loop in the module will keep printing recursively. However in this case there is no exit. This isn’t something you would do lightly.

An external bool could act as an exit for this.

while keepGoing.Value do task.wait(0.1)
	print(module.functionName("hello"))
end

Honestly can’t think of a single case I would ever do something like this.

You don’t nor shouldn’t be using pseudo-classes for this. They are slow and painful to work with, especially since Lua is a dynamic prototyped language.

What you are looking for is called the callback pattern. You pass or mutate a function in your interface for it to be called by another process internally. This is similar to Roblox’s RBXScriptSignal, except only one callback is allowed and thus you can’t create race conditions.

-- Module
local Interface = {}

Interface.Value = nil
Interface.OnChanged = nil

function Interface:Set(Value)
	self.Value = Value
	
	if self.OnChanged then
		self.OnChanged(Value)
	end
end

return Interface
-- Consumer
local Interface = require(Module)

Interface.OnChanged = function(Value)
	print(Value)
end

Interface:Set("Hello")

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