Table Scope Blocks

lua-users home
wiki

In Pascal there is a technique to put the data members in a record into scope. I propose we do the same, with a structure like this:

A = {}

using A in
    foo = 5;
    bar = "Hello World";
end

write(A.foo, A.bar) -- Will print out "5Hello World"

The basic method for doing this is replacing the global scope with a table scope while in the block. Since this is a block, it guarantees that global scope will never be lost.

This could be useful in OO implementation in Lua, to make better use of self. If you put self in scope, then it would be more "C" like again:

function A:foo(x)
    local y
    bar = x -- Sets self.bar to x  [and where comes x from? --ET]
    y = x -- Sets local variable y
    self.y = x -- Sets self.y
end

Could probably complete this example to show exactly how to set the tags

This would require the use of the function tag, where a using block is placed around the actual function call.

This may also help when creating Lua packages. In python, if a module uses global scope, it actually accesses variables in the module dictionary. With a little work, the same effect could be created with a "using..in" block.

There's also the question of how this will work with the above recommendation that variables be assumed local.


1. How do you access the global scope when 'using' is active? In typed languages like C++ or Pascal the compiler knows which identifiers are globals or class/structure members and generates appropriate code. Lua does not know...

2. I find it pretty annoying in i.e. C++ that you cannot see whether an identifier is class member or a global. You have to look up the class definition. Writing self.x makes it clear that a field instead of a global is accessed. I have to agree here. Many C++ Programmers even use the convention to declare all member variables beginning with m_... to make it clear that when it is used, a membervariable is accessed. --PeterPrade

--ET


The first example can be done using :

tab = { tab2={ x=3 } }
do local t = tab.tab2
  print (t.x)
  t.x = 4
end

print (t) -- nil as out of scope now

--NDT


RecentChanges · preferences
edit · history
Last edited July 7, 2007 7:22 pm GMT (diff)