Reputation: 19
Im starting to learn Lua modules a bit, and I am having troubles with a small part in my Lua. Everytime I change my variable it reverts back to nil.
myModule.lua
--I should note that client is a number.
module(..., package.seeall)
local LoggedIn = { }
function isLogged( client )
return LoggedIn[client]
end
function logIn(client)
table.insert(LoggedIn,client,true)
end
function logOut(client)
table.remove(LoggedIn,client)
end
main.lua an event happens
package.loaded.myModule= nil; require "myModule"
function event( client )
myModule.logIn(client)
end
function event_2( client )
myModule.logOut(client)
end
EDIT: Using functions instead, and making it local variable. It is still returning nil even though I can confirm the logIn function happened with no errors. Without even using the logout function yet. Any thoughts?
but later on in main.lua I check if client is logged in and it just returns nil.
Is this just a limitation of modules or am I just accessing the variable wrong.
I should note I need to be able to do this in other Luas that acces myModule.lua too.
Thanks in advance
Upvotes: 1
Views: 3178
Reputation: 26794
The following using your own code (assuming you fix typo in funtion
) works (it prints true\nnil
):
package.loaded.myModule= nil; require "myModule"
function event( client )
myModule.LoggedIn[client] = true
end
event("foo")
print(myModule.isLogged("foo"))
A better way to do this would be to add a function logIn
as @Mike suggested and avoid using module(); you can use something like this instead:
local myModule = require "myModule"
function event( client )
myModule.logIn(client)
end
event("foo")
print(myModule.isLogged("foo"))
print(myModule.isLogged("bar"))
And myModule.lua
becomes:
local LoggedIn = { }
function isLogged( client )
return LoggedIn[client]
end
function logIn( client )
LoggedIn[client] = true
end
return { LoggedIn = LoggedIn, isLogged = isLogged, logIn = logIn }
Upvotes: 1
Reputation: 14564
You don't really give us enough code to fully help you, but this is a working example I set up based on what little example you gave us:
-- myModule.lua
module(..., package.seeall)
LoggedIn = {}
function isLoggedIn(client)
return LoggedIn[client] ~= nil
end
function LogIn(client)
LoggedIn[client] = true
end
function LogOut(client)
LoggedIn[client] = nil
end
and to test it:
-- main.lua
require "myModule"
myModule.LogIn("Joe")
myModule.LogIn("Frank")
print(myModule.isLoggedIn("Bill"))
print(myModule.isLoggedIn("Frank"))
myModule.LogOut("Joe")
print(myModule.isLoggedIn("Joe"))
this prints out as expected:
false
true
false
so my guess is that you are not checking the conditions correctly for LoggedIn[client] being empty, or you never actually remove entries from the LoggedIn table when someone 'logs out'.
Upvotes: 1