A local variable cannot be visible in closing by file?

Suppose I have the following two Lua files:

In a.lua:

local x = 5
f = dofile'b.lua'
f()

In b.lua:

local fun = function()
  print(x)
end
return fun

Then, if I run luajit a.luain the shell, it prints nil, since it xcannot be seen in the function defined in b.lua. Expected print should be 5. However, if I put everything in one file, then this is exactly what I want:

In aa.lua:

local x = 5
local f = function()
  print(x)
end
f()

Run luajit aa.luaprints 5.

So why xnot see in the first case?

+4
source share
3 answers

As their name implies, local variables are local to the block.

dofile() . , , x .

+4

, , .

, , "" - , , , .

dofile, , , , -, . , "dofile" C/++, , , , .

, " , ". , , ', X' ', Y .

, , , , loadfile/dofile, -. lua " , () , () ". , .

, - , . , , .


, , , , - script , script, . , dofile . lua 5.1 vs lua 5.2.

lua 5.1:
a.lua:

local shared = { x = 5 }
temp = loadfile('b.lua')
setfenv(temp, shared)
f = temp()
f()

lua 5.2:
a.lua:

local shared = { x = 5 }
temp = loadfile('b.lua', 't', shared)
f = temp()
f()
+1

x, a.lua, b.lua, ​​. - .

, x b.lua, . . , .

a.lua

x = 5
f = dofile'b.lua'
f()

b.lua

local fun = function()
  print(x)
end
return fun

.

, _G. Lua , , Lua . b.lua :

local fun = function()
  print(_G["x"])
end
return fun
+1

Source: https://habr.com/ru/post/1613056/


All Articles