lua-users home
lua-l archive

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



One thing you can do with generic Lua syntax is to let 'foo:define()' return a function that will take the actual function argument in. I've used this in at least a 'switch' implementation, once.

You will still need paranthesis around the function. To do without them, you'd need a syntax modifier s.a. luaSub or MetaLua.

Would look like:

   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 )

Another approach could be to set them just via table overrides (__newindex metamethod):

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

-asko



On Thu,  5 Jun 2008 11:11:13 +0200
 Eike Decker <eike@cube3d.de> wrote:
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