Hello, I’m trying to iterate through the keys of a table in a module script one by one when Q is pressed. However, output is printing nil.
Here’s the LocalScript:
local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Module = require(ReplicatedStorage:FindFirstChild("ModuleScript"))
UserInputService.InputBegan:Connect(function(input, isTyping)
if isTyping then return end
local currentIndex = 1
local Table = Module
local function iterateTable()
if currentIndex <= #Table then
local value = Table[currentIndex]
currentIndex = currentIndex + 1
return value
elseif currentIndex > #Table then
currentIndex = 1
end
end
if input.KeyCode == Enum.KeyCode.Q then
local value = iterateTable()
print(value)
value = iterateTable()
end
end)
The table inside of your module script has string keys, and you are trying to access the values inside of the table with an integer index. No values in your table have an integer index, so you get a nil value.
Try changing your module script to this instead:
local module = {
"Idle",
"Active",
"Disabled"
}
return module
This way, Module[1] = “Idle”, Module[2] = “Active”, and Module[3] = “Disabled”.
Found the problem, not obvious at all but #Tablealways returns 0 when it’s not an indexed table.
What I did to solve that problem was to write a function len(table) which would return the length of the table like this :
local function len(Table)
local length = 0
for i,v in Table do
length += 1
end
return length
end
Don’t believe this is the issue, yes you’re defining Module within the local scope, but you’re also returning, so that any script requiring it, returns the table.
This is basically the same thing, you’re just defining “table” in the Module table.
It’s not actually a global variable.
It’s just like when you declare a function in a module…
function Module.NamedFunction()
end
He’s directly defining the info in the module table, which is fine. But, as @DemGame pointed out, he’s incorrectly accessing the table.
And as well as @1_Lukeskyiwalker pointed out, he’s not finding the correct length with # and needs to use something similar/just like the function @1_Lukeskyiwalker gave.