materia-nigra
materia-nigra

Reputation: 85

Why loading a module to a local or global variable imply in different results depending on the module in Lua?

The module lfs seems to be accessible indifferently whether assigned to a local or global variable:

> lfs = require 'lfs'
> print(type(lfs))
table
> local lfs = require 'lfs'
> print(type(lfs))
table

The same does not occur with md5:

> md5 = require 'md5'
> print(type(md5))
table
> local md5 = require 'md5'
> print(type(md5))
nil

What explains the difference?

Upvotes: 2

Views: 60

Answers (1)

Paul Kulchenko
Paul Kulchenko

Reputation: 26764

It's because lfs calls lua_setglobal(L, LFS_LIBNAME);, which sets global lfs variable, so it's available even when you do local lfs = require "lfs". md5 doesn't do that.

As noted in the comments, if you run this from a Lua interpreter, you need to take into account that local is only visible for the same line, so running > local a = 1 and >print(a) will show nil. It's not nil for lfs only because it also sets (implicitly) a global variable with the same name (as explained above). If you run local mylfs = require "lfs" and then print(mylfs), the results for lfs and md5 will be the same.

Upvotes: 1

Related Questions