Question

Based on SimpleLuaClasses I've done a class in a file:

require 'class'

Session = class(function(self)
    self.session_name = "l_sid"
end)

function Session:init(r)
    self.session_id = r:getcookie(self.session_name)
    if not self.session_id then
        self.session_id = r:sha1(tostring(r.log_id) .. r.clock())
        r:setcookie({
            key =   self.session_name,
            value = self.session_id
        })
    end
end;

Now I'm trying this:

local session = require 'session'

function handle(r)
    local s = Session()
    s:init(r)
end

The previous code works. If I try local s = session.Session() it doesn't work.

When I try this, I get this error:attempt to index upvalue 'session' (a boolean value).

Why?

Was it helpful?

Solution 2

Here's a version that works:

--[[
--------------------------------------------------------------------
Classe Session
]]--
require 'class'

local session = {}

session.Session = class(function(self)
    self.session_name = "l_sid"
end)

function session.Session:init(r)
    self.session_id = r:getcookie(self.session_name)
    if not self.session_id then
        self.session_id = r:sha1(tostring(r.log_id) .. r.clock())
        r:setcookie({
            key =   self.session_name,
            value = self.session_id
        })
    end
end;

return session

OTHER TIPS

The return value of the require function is the value returned from your module. For example, if you create a file "foo.lua" with the following contents

-- This is foo.lua
return 17

When you do in another file

local x = require 'foo'
print(x)

Its going to print 17.

In your case, in order to have session.Session work you would need to return a table with a Session field from "session.lua"

return { Session = Session }

Alternatively, you can also just return Session directly if you aren't returning anything else

-- in session.lua
return Session

-- in the other file
local Session = require 'session'

Finally, the reason your first sollution is working is that you are defining Session as a global variable, that is seen from every module. I would recommennt avoiding globals as much as possible so you can turn Session into a local in session.lua

local Session = class(function() ... end)

Compiling everything together, here is how your fiull session.lua file should look like

require 'class'

local Session = class(function(self)
    self.session_name = "l_sid"
end)

function Session:init(r)
    self.session_id = r:getcookie(self.session_name)
    if not self.session_id then
        self.session_id = r:sha1(tostring(r.log_id) .. r.clock())
        r:setcookie({
            key =   self.session_name,
            value = self.session_id
        })
    end
end;

return Session
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top