lua-users home
lua-l archive

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


Hi

I wondered today about function calls in lua and there exist function calls that
don't require round brackets, i.e. 

require "modulex"

or

dothis {1,2,3}

What I wanted to do today is to figure out how a table could provide a
polymorphic function call. So I wanted to construct a table which is a
collection of multiple functions that are each called depending on the passed
arguments. Well, it's more theory than practical, but I wondered how to
implement such a system in lua ;).

So I thought about this

foo = polymorphic()
foo:define(function () print "no arg" end)
foo:define("number",function (num) print("number:",num) end)
foo:define("string","number",function (str,num) print("str,num:",str,num) end)

foo() -- "no arg"
foo(1) -- "number: 1"
foo("blah",1) -- "str,num: blah 1"

So that's the idea and it should work that way, however I wondered if I could
leave the brackets away when defining the functions, which could look this
way:

foo:define 
  function () 
    print "no arg" 
  end

foo:define "string" "number" 
  function (str,num) 
    print("str,num:",str,num) 
  end


Compared with the currently required syntax, it's a little bit more beautiful.
For example

foo:define "string" "number" ( -- opener must be here
  function (str,num) 
    print("str,num:",str,num) 
  end)

I wonder now if the brackets could be left away without confusing the compiler,
just like it is the case with strings. 
Since it's a anonymous function declaration, the compiler is right now aware
about the fact that something must be done with it - just like a string causes
either a call or is assigned to a variable.

So could this be a language feature or would it not work (due to something that
I am right now not aware of) or would it be too confusing?

Eike