Cannot import module with Lua, results in attempt to index global 'test' (a nil value)

爷,独闯天下 提交于 2019-12-07 12:38:26

To expand on lhf's answer:

The Lua shell reads one statement at a time. It then loads the code string with the loadstring function (or more accurately, the C API equivalent), which compiles the Lua code and returns a function that executes it. Since each statement is loaded separately, and produces a different function, they don't share local variables.

Essentially, this console input:

local test = require "test"

print(test)

if test then
    bar()
end

Is translated to this:

(function() local test = require "test" end)()

(function() print(test) end)()

(function()
    if test then
        bar()
    end
end)()

(Note that this applies to files as well. Lua 'files' are actually just functions with an implicit function(...) signature. This means you can return from the top-level of a file, as well as perform any operations you can do on functions (sandboxing, etc) on files as well.)

If you're copying code from somewhere, you can surround the code in do ... end, like so:

do
    local test = require "test"
    print(test)
end

The do ... end block counts as one statement, and scopes local variables.

In the interactive Lua shell, each complete statement is executed as read. Local variables do not survive from one statement to the other.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!