lua-users home
lua-l archive

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


It looks alright to me, but you'll incur some overhead every time you
call lib.foo as _G.foo.  If this is a problem and you've got memory to
spare, you could do this:

local mt = setmetatable(_G, {})
local lib = _G.lib

function mt:__index(key)
  if [key is one of a list of possible keys] then
    local f = lib[key]
    self[key] = function()
      print('Warning! Deprecated usage of function ' .. key)
      return f(...)
    end
    return self[key]
  else
    return nil
  end
end

This method ends up caching the lookups.

-Rob

On Thu, 09 Dec 2010 18:21:12 +0100
Francesco Santini <rincewind@tin.it> wrote:

> Dear list,
> 
> I am working on a project where Lua is embedded inside a larger C 
> environment. In a previous version, I had registered some C functions
> as Lua globals (through lua_register), thus polluting the global
> scope.
> 
> Now I would like to do things right, so I registered the same
> functions as members of a table (say "lib"), so that they are called
> as lib.myfun() instead of just myfun().
> 
> However, I would like to keep some support for the "global"
> convention, as I cannot expect all the scripts to be ported to the
> new convention immediately. But at the same time I would like to
> print a warning whenever a function is called as global before
> falling beck to lib.xxx.
> 
> I implemented a version that adds a metatable to _G that defines the 
> __index metamethod more or less like the following:
> 
> mt = {}
> 
> mt.__index = function(table, key)
> 	if [key is one of a list of possible keys] then
> 		print("Warning! Deprecated usage")
> 		return lib[key]
> 	else
> 		return nil
> 	end
> end
> 
> setmetatable(_G, mt)
> 
> 
> I tested it and it seems to work, but I am a bit worried about adding 
> such a metamethod to the global environment. Is it a good idea? Is
> there some loophole that I might fall into in some cases? Is there a
> better way of achieving my goal?
> 
> Thanks!
> 
> Cheers,
> 
> Francesco
> 

Attachment: signature.asc
Description: PGP signature