lua-users home
lua-l archive

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


Thanks for the idea.

Florian


> On Tuesday, Jan 21, 2003, at 08:37 Europe/Copenhagen, Florian Berger
> wrote:
>
> > Now my system can check what kind of functions are in system and what
> > they
> > return and require as parameters. I think now it is possible to add so
> > many functions as possible. How good is this idea and are there any
> > other
> > ideas?
>
> Maybe have a table where the key is the argument type and the value is
> a table of functions that take that type as argument, and these
> functions are indexed (keyed) according to their result.
>
> Example (though better build this structure programmatically):
>
> allFilters = {
>      -- functions that takes a diameter as argument
>      "diameter" = {
>          "radius"   = function (d) return 0.5*d end
>      }
>      -- functions that takes a radius as argument
>      "radius"= {
>          "diameter" = function (r) return 2*r end
>          "area"     = function (r) return 2*math.pi*r*r end
>      }
> }
>
> Then to get a function that converts from type A to type B you would do
>
> function convert (A, B)
>      t = allFilters[A] -- table of all functions that take A as argument
>      f = t[B]          -- function that takes A and returns B, or nil if
> none exists.
> end
>
> E.g. convert("radius", "area") will be
>      t = allFilters["radius"]
>      f = t["area"]
> and that is the function which converts the radius to a circle area.
>
> Now in case f is nil, then you simply do an 'foreach' on t (which
> traverse the table of functions that understand your current argument,
> and as key tell you the result) and call 'convert' recursive, but with
> the current key as argument instead of A.
>
> So convert("diameter", "area") will give:
>
>      "diameter" = {
>          "radius"   = function (d) return 0.5*d end
>      }
>
> This table has only one key ("radius") and we call recursive with that
> as A:
>      convert(A: "radius", B: "area")
> and this will give us the function...
>
> Of course you would have to avoid cycles -- this could easily be done
> by using a table instead of a function and have a (boolean) field which
> you set true when you use the function and back to false when you
> return from the recursion (and skip functions which have the field set
> true).
>
> The chain of functions to be used is implicitly given through the stack
> when a recursion finally finds a function that works, you could return
> a table with the functions (and each recursion would append one to this
> table) or you could just give the value to be converted as a third
> argument, and simply let the function return the converted value (so on
> each recursion you would do a conversion).
>
> Regards Allan
>
>