Table Scope Blocks

lua-users home

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";

write(, -- 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 to x  [and where comes x from? --ET]
    y = x -- Sets local variable y
    self.y = x -- Sets self.y

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 "" 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


The first example can be done using :

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

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


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