lua-users home
lua-l archive

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

On Thursday, November 28, 2013, Dirk Laurie wrote:
2013/11/28 Andrew Starks <>:

> What really happens, and where I get stuck , is in cases where I want to
> provide flexibility in the interface to a function.
> Example:
> I have an object that holds a sequence. I would like to provide a way to
> accept that object or a sequence of them. Knowing that I have one object or
> many can be non-trivial, especially if I'm likely to get them from somewhere
> other than a typical lua oo implementation.
> Another example is a string. Everything can have tostring called on it. If I
> want my function to accept a table or a string, how do I know that I don't
> have an object that is trying to quack like a string?

 Is XML lurking under the surface here?

More generally, parsing is an excellent example of where this comes up. I may have what amounts to an object, but I'm getting it from inputs, like an LPEG match. 

> In Lua. 5.3 or in the future, it'd be cool if making flexible interfaces to
> functions could be made simpler, without sacrificing polymorphism.

I'm not sure I understand exactly what a flexible interface would be like,
but the examples suggest something like this:

function handler(thing)
    if type(thing)~='table' then -- handle scalar case
    elseif thing.handler_can_handle_it then -- handle object case
        result={} -- if required
        for k=1,#thing do
           -- or maybe -- thing[k]=handler(thing[k])
           -- or maybe -- result[k]=handler(thing[k])
         return result
         -- or maybe -- return thing

Is that what you are after?

 You're understanding it. I'm suggesting that a simple mechanism to avoid an over abundance of that kind of code would be nice. 

Often, it's when I'm calling the function where I feel the need. 

For example, I can "tostring" a table for a setter function that does A if it gets a string and B if it gets a table, when I want behavior A, which might be, "store the value as a property". But then I loose the capabilities of the object, which often means re-parsing it or somehow referencing it, if possible, on every `get`. 

It would be cleaner if the function just stored the string-quaking table and used it as a string, so if it's my setter, I sometimes try to refactor with evermore sophisticated introspection. This works and is what it is, sometimes. 

I want to stay away from suggesting a particular design (in the same away I appreciate use cases over feature requests)... For as long as I can at least. :)

But the general idea is that some subtle help in this area appears to have a large number of use cases, in my experience.