lua-users home
lua-l archive

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


On Friday 30, Petite Abeille wrote:
> On Mar 30, 2012, at 11:22 PM, Petite Abeille wrote:
> > But now when running the resulting Nanoki.luac in 5.2, I get the following 
exception:
> For what's worth, here is a self-contained example of the issue:
> 
> 
> $ cat TestA.lua
> local print = print
> 
> module( 'TestA' )
> 
> print( _NAME )
> 
> 
> $ cat TestB.lua
> local print = print
> 
> module( 'TestB' )
> 
> print( _NAME )
> 
> 
> $ cat TestC.lua
> local TestA = require( 'TestA' )
> local TestB = require( 'TestB' )
> 
> print( 'TestC' )
> 
> 
> $ lua -v TestC.lua
> Lua 5.2.0  Copyright (C) 1994-2011 Lua.org, PUC-Rio
> TestA
> TestB
> TestC
> 
> 
> $ luac -o TestC.luac TestA.lua TestB.lua TestC.lua
> 
> 
> $ lua TestC.luac
> TestA
> lua: TestB.lua:3: attempt to call global 'module' (a nil value)
> stack traceback:
> 	TestB.lua:3: in main chunk
> 	(luac): in main chunk
> 	[C]: in ?
> 
> 
> Thoughts?

luac is combining those files into this:
-- TestA.lua
(function()
  local print = print

  -- first call to module.  Under Lua 5.2 it changes _ENV for the
  -- whole compiled group of files.
  module( 'TestA' )

  print( _NAME )
end)()
-- TestB.lua
(function()
  local print = print

  module( 'TestB' )

  print( _NAME )
end)()
-- TestC.lua
(function()
  local TestA = require( 'TestA' )
  local TestB = require( 'TestB' )

  print( 'TestC' )
end)()

In Lua 5.1 the 'module' call only affects the anonymous (function()end) 
function's environment.  In Lua 5.2 all of the (function()end) blocks share 
one _ENV up value.  So the first call to module() in TestA.lua changes the 
_ENV for all the other modules.

One solution would be to add this code:
local _ENV = original_ENV

before each (function() ...... end)() block.  "original_ENV" would have to be 
saved at the start:
local original_ENV = _ENV

Or to wrap each block with a do/end block:
do
  local _ENV = _ENV
  (function()
   --- files code
  end)()
end

This could be done by modifying the Lua compiler written in Lua [1].

1. http://lua-users.org/wiki/LuaCompilerInLua

-- 
Robert G. Jakabosky