Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

I can't make a module script find a bool value from normal script?

The First script is suppose to find if we are in Studio then transmit that hi bool value to the module script where it goes to the function. Thing is, it doesn't work. Why exactly is that?

MainMouduleLol.Check(hi)
if game:GetService('RunService'):IsStudio() == true then
	hi = false
else
	hi = true
end

MainMouduleLol.Check = function(hi)
if hi == true then
	if	game.CreatorId == 16616858 	then
		wait(1)		
		print("Nice ")
	else
		wait(1)
		print('Not really nice')
			end
else 
	print('We are in studio!')
end
end

1 answer

✓ Accepted answer

There's a lot of reasons why this doesn't work, you seem to misunderstand the meaning of variables.


References

When you say something like foo(hi), that gives the function foo the value of hi at the time of this call . For this, that would be either true or false.

If I later change hi, that doesn't affect foo -- the value was already decide a while ago.


Timing

The Check function only gets run once -- right when you call it. That's before you set hi. So modifying hi afterwards doesn't accomplish anything anyway.


How to write this right

There's no reason for a Script to try to give information to the ModuleScript -- the ModuleScript is perfectly capable of asking RunService itself.

Storing state in modules

If you do want to send information to a modulescript, you have to explicitly store it somewhere.

Here's a simple counter module. Calling module.set(n) will set the counter to n, and callign module.count() will print the count and tick up once:

module = {}
number = 0

function module.set(n)
	number = n
end

function module.count()
	print(number)
	number = number + 1
end

return module

-- usage:
-- module = require(mymodule)
-- module.set(5)
-- module.count() --> 5
-- module.count() --> 6
-- module.set(1)
-- module.count() --> 1

If you really want to engineer things well, you should avoid global variables (count). Global variables will often come to bite you later.

Instead, variables should always belong to an object -- that way, you can easily have more than one counter at a time:

module = {}

local function set(self, n)
	self.number = n
end

local function count(self)
	print(self.number)
	self.number = self.number + 1
end

function module.new(n)
	return {
		number = n,
		set = set,
		count = count,
	}
end

return module
-- usage:
-- Counter = require(mymodule)
-- m = Counter.new()
-- m:set(5)
-- m:count() --> 5
-- m:count() --> 6
-- m:set(1)
-- m:count() --> 1

This discussion is preserved as it was. New answers, comments, and votes are closed.