You could use tables or use the "var" variable, both works, but the reason that your script doesn't work is probably because you never defined the "var" variable, that means that the script thinks "var" is equal to nil (nothing). So you're basically checking
if (nil == 1) then
You can define the variable. Also to avoid repeating the if statement and module requiring, you COULD use a table, but if you want to have a name like "module1", "module2" "module10" etc, you can concatenate strings to find the name of the module to find, concatenation is a way to connect two strings together. It's supposed to be a "..", For example,
local a = "Hello"
local b = "Roblox"
print(a..b)
print(a.." "..b)
You could find the module using this
local moduleName = "module"..var
Here is the full script
local var = 1
local function onInputBegan(inputObject, gameProcessedEvent)
if gameProcessedEvent then return end
if inputObject.KeyCode.Name == "F" then
local moduleName = "module"..tostring(var)
if (game.ReplicatedStorage:FindFirstChild(moduleName) and game.ReplicatedStorage:FindFirstChild(moduleName):IsA("ModuleScript")) then
require(game.ReplicatedStorage[moduleName])
end
end
end
If you wanted to, you could still use an array for this.
An array is basically a table which can hold any values. Arrays have to be indexed using a number. For example
local fruits = {
"Oranges",
"Apples",
"Mangoes",
}
print(fruits[1])
fruits[1] = "Tomato"
print(fruits[1])
We can also use the "#" symbol to get the amount of keys in the array. For example
local a = {"A", "B"}
print(#a)
a[#a + 1] = "C"
print(#a)
Since your "var" variable is a number, it can be used as an index.
This is your script with a table
local var = 1
local modules = {
game.ReplicatedStorage.module1,
game.ReplicatedStorage.module2,
game.ReplicatedStorage.module2
}
local function onInputBegan(inputObject, gameProcessedEvent)
if gameProcessedEvent then return end
if inputObject.KeyCode.Name == "F" then
local module = modules[var]
if (module and module:IsA("ModuleScript")) then
require(module)
end
end
end
1 comment
Thanks so much! This helped a lot.