Skip to content

how to use require? #14

Closed
Closed
@luoqi

Description

@luoqi

i use require like:
local xxx = require('xxx')
but,it also haven't to work.

--test.lua
function a()
ngx.print("test.lua");
end;

a();

--concat.lua
local test=require("test");


at the first request,it print:
test.lua

and,the next time,have nothing print;

Activity

agentzh

agentzh commented on Jan 24, 2011

@agentzh
Member

This is more like a Lua question. To understand why this happens, see http://www.lua.org/manual/5.1/manual.html#pdf-require

To quote the key sentence:

"The (require) function starts by looking into the package.loaded table to determine whether modname is already loaded. If it is, then require returns the value stored at package.loaded[modname]. Otherwise, it tries to find a loader for the module. "

That is, Lua's "require" will not re-load a module for the sake of performance.

So you're coding up Lua modules in a totally wrong way. We usually use Lua modules this way instead:

-- test.lua
module("test", package.seeall)
function a()
    print("test.lua")
end

And then in your content_by_lua_file directive's lua file:

-- concat.lua
local test = require("test")
test.a()

You will see the "test.lua" output on every request as you'd expect.

luoqi

luoqi commented on Jan 24, 2011

@luoqi
Author

thank you!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @agentzh@luoqi

        Issue actions

          how to use require? · Issue #14 · openresty/lua-nginx-module