在Tar​​antool上热重装Lua应用程序时出现问题

问题描述

我正在尝试热重载Lua模块,但是在我看来,这种方法似乎不起作用。

我创建了2个简单的示例模块“ app.lua”和“ test.lua”,其中前一个用作应用程序的入口点:

# app.lua
test2 = require("test")

while 1 > 0 do
    test2.p()
end

并从后者中加载一个函数

# test.lua
local test = {}
function test.p()
    print("!!!")
end

return test

此应用程序正在从官方Tarantool映像构建的docker容器中运行。假设我已经对'test'模块的代码进行了更改,例如,将print行更改为'print(“ ???”)'。重新加载模块的标准方法是在容器上进入tarantool控制台,并将nil分配给package.loaded['<name_module>']。但是,当我键入它时,控制台会说它已经为空:

tarantool> package.loaded['test']
---
- null
...

我在做什么错了?

解决方法

您可能会看到package.loaded['test'] == nil,因为您没有连接到Tarantool实例。

通常,当您连接到Tarantool时,您看起来就像

connected to localhost:3301
localhost:3301> 

似乎您只需输入docker容器,然后 运行“ tarantool”。这样,您只需运行对您的应用程序一无所知的新Tarantool实例。

您可以使用console命令(在容器中)或tarantoolctl connect login:password@host:port(对于默认配置tarantoolctl connect 3301有效,有关详细信息,请参见here)或{{ 3}},然后检查package.loaded['test']的值。

这是一种用于重新加载模块代码的简化方法:

test2 = require("test")

local function reload()
    package.loaded['test'] = nil -- clean module cache
    test2 = require('test') -- update a reference to test2 with new code
end

while 1 > 0 do
    test2.p()
end

return {
   reload = reload,-- require('app').reload() in your console for reload
}

更复杂,但正确的方法是使用attach模块。

以下是您的代码无法正常工作的说明:

-- Here you require "test" module
-- Lua check package.loaded['test'] value
-- and if it's nil then physically load file
-- from disk (see dofile function).
--
-- Well,you got a reference to table with
-- your "p" function.
test2 = require("test")

-- Here you've already has a reference
-- to "test" module.
-- It's static,you don't touch it here.
while 1 > 0 do
    test2.p()
end

然后您进行package.loaded['test'] = nil并 从package.loaded表中删除密钥。 请注意,您不会因为拥有 您的“ app.lua”文件中的引用(以您的情况为test2)。