lua-users home
lua-l archive

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


On 28 Dec 97 at 19:24, Steve Dekorte wrote:
> I'm having problems getting Lua to do something like Smalltalk/Self
> blocks.
(...)
>    myCollection:do( function myBlock(a) if a:isGreaterThan(24) 
>       then a:increment() end end )
(...)
> But I get a syntax error when I try to declare a function within a
> function. Is there any way around this syntax error problem?

First of all, I've been told in Lua 3.1 this problem will vanish -- 
code like that you specified will be feasible.

In the meantime, you can try using strings to define the functions to 
be passed. For example,

 func_body = "if param1:isGreaterThan(24) then param1:increment() end"
 myCollection:do( func_body )

 (...)

 function myCollection:do ( func_body )
   local param1;

   param1 = whatever;

   dostring( func_body )
 end

(Of course, the temporary variable func_body is used here only to 
tidy up the code a bit.)

That, of course, requires a specific parameter name to be specified 
(in this case, 'param1'). But there's another way to handle it -- you 
can specify a full function in the string (with a specific name and 
parameter order, but of course, free parameter names). For example:

my_func = [[
  function Iterate ( p )
    if p:isGreaterThan(24) then 
      p:increment()
    end
  end
]]

(I find the [[ .. ]] construction extremely useful for this kind of 
thing.)

Now, 'Iterate' is the locked name, and the parameter 'p' could be 
named after whatever your heart desired. myCollection:do would look 
something like this:

 function myCollection:do ( func_body )
   local param1;

   param1 = whatever;

   dostring( func_body )

   Iterate( param1 )
 end

... or anything like it. Of course, another solution would be for a 
second parameter be the function name specifier, but that goes way 
over my point.

And here's a suggestion: before executing the dostring, you can check 
the parameter type. That way, myCollection:do can receive as 
parameter either a string or a function.

Hope this helps.

	Pedro

----------------------------------
    Pedro  Miller Rabinovitch
    miller@tecgraf.puc-rio.br
----------------------------------

Worst Vegetable of the Year:
The brussels sprout. This is also the worst vegetable of next
year.
Steve Rubenstein