lua-users home
lua-l archive

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



On 9 Oct 2006, at 13:49, Paul Hudson wrote:

It would be nice if Lua had a (psuedo?) table that gave the current value of any identifier if indexed by that identifier, whether that's a local or not

Of course, someone will now reply and tell me it already exists.

Can you play games with __index and the function environment to get a table
that works like that? I can't seem to get my head around this today.

Well, the information about locals is only available via the debug API. And it's fairly slow to access. But here's some starter code:

function locals(level)
  level = level or 2
  local i = 1
  local t = {}
  while true do
    local n, v = debug.getlocal(level, i)
    if n == nil then
      return t
    end
    t[n] = v
    i = i + 1
  end
end

function foo() local x,y=1,2 for i=1,4 do for k,v in pairs(locals()) do
print(k, v) end x=x+1 y=y*2 end end

foo()

locals is a function that returns a table of local variables with the name of the local being the key and its value (at the time that locals () was called) being the value. That would be suitable for passing to the Python-like % operator that is being discussed. It won't be very quick.

drj




P.

-----Original Message-----
From: lua-bounces@bazar2.conectiva.com.br
[mailto:lua-bounces@bazar2.conectiva.com.br] On Behalf Of
askok@dnainternet.net


Passing the local variables as a kind-of identity matrix
is not too bad:

local me= "asko"
local age= 36

print( "My name is $me and my age is $age."     % { me=me,
age=age } )

print( "My name is ${me} and my age is ${age}."     % {
me=me, age=age } )


Global values can be pointed to like such (unless the %
operator wants to default fall-back to them):

print( "This is a global value: ${print}" % _G )