lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> Am I missing a required flag here? Is this expected behavior?

Yes, because "module()" function was deprecated and removed later
(https://www.lua.org/manual/5.2/manual.html#8.2).

You can change `_G` to `(_ENV or _G)`, but it's not going to work
either, because `module()` is not going to put "shared_module" into a
global namespace, so the script will fail with "attempt to index
global 'shared_module' (a nil value)".

You'll have to change it to return the module table to make it work in
Lua 5.1+. Something like this should work:

```
package.preload['sub_module1'] = (function(...)
   --module("shared_module");

   local sub_module1 = {}

   function sub_module1.add(a, b) return a + b; end
   return sub_module1
end)

local module_file = require('sub_module1')
num = module_file.add(1, 2)
print(num)
```

Paul.

On Thu, May 11, 2023 at 9:14 AM Andrew Kaiser <kaisea.rpi@gmail.com> wrote:
>
> Hi, I noticed a problem when building lua 5.2 with LUA_COMPAT_ALL defined. I need to use the "module" function, but it seems to be broken in 5.2? Take this snippet for example:
> ```
> package.preload['sub_module1'] = (function(...)
>    module("shared_module");
>
>    sub_module1 = {}
>
>    function sub_module1.add(a, b) return a + b; end
> end)
>
> require('sub_module1');
>
> local module_file = _G['shared_module']['sub_module1'];
> num = module_file.add(1, 2);
> print(num);
> ```
>
> Running this with lua 5.1 will output `3`. Running this with lua 5.2 will output the following error:
> ```
> ./src/lua: ../../sample.lua:11: attempt to index global '_G' (a nil value)
> stack traceback:
> ../../sample.lua:11: in main chunk
> [C]: in ?
> ```
>
> everything appears to get wiped from the global scope, including "_G", "require", "print", etc. It seems to happen in this `set_env` function https://www.lua.org/source/5.3/loadlib.c.html#set_env when we load the `ll_module` c function. I was able to repro this with the default `make macosx` command and the lua interpreter for 5.1.5 and 5.2.4. Am I missing a required flag here? Is this expected behavior?