lua-users home
lua-l archive

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


>From lua-l@tecgraf.puc-rio.br Wed Jun  9 16:38:00 1999
>From: David Jeske <jeske@chat.net>
>
>I'm confused about how this works. Correct me if I'm mistaken, but
>functions do not inherit their tag methods when they are defined.

Right.

>They>use the tag methods which are setup when they are called.

>I believe
>the above solution will only work if the execution of code in the
>chunk begins and ends completely within the chunk. If you define a
>function within the chunk which uses global variables, and you call
>that function after the chunk is loaded, the variables are no longer
>chunk local.

Right.

>Is some of my analysis incorrect? Can you think of a way to get
>chunk-local variables which work even when you call functions after
>the chunk is loaded?
>
>The only method I can think of involves overriding the global set and
>table set tag methods to detect function assignments and have them
>create wrapper functions which set the tag methods appropriately.

That's the only way I can right now.

>This definetly won't have good performance consequences

I can say withou testing. You'd be amazed how fast Lua is?
(Or, to say it differently: in a interpreted language, everything is more or
less slow, so what difference could this make?)

>would give the desired effect (i.e. a chunk/module variable scope).

If your functions never *set* global variables, then it is easier and cleaner
to use upvales:

 local A="something"
 ...
 function f(x,y,z) print(%A..(x+y+z)) end

The % is not hard to write and is signals an access to a "global" var.
if you need to set "global" variables, then the best solution seems to use
a local table explicitly:

 local G={}
 ...
 function g(x,y) %G.sum=x+y end


The tag method game I posted was simply to make a point.
the solutions above seem to me to be much simpler and cleaner, and within
the philosophy of Lua.

We're planning an extensible preprocessor, which will make this even easier
to write. The code above could be written as something like:

 local G={}
 ...
 function g(x,y) $$sum=x+y end

$$ would invoke a user function called "$" *during* compilation and this
function could return "%G." to the lexer.

--lhf