lua-users home
lua-l archive

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


On Feb 11, 2008 6:30 PM, Ben <thebassplayer@gmail.com> wrote:
> Back to the point, callables and such... seem against the Lua Way from
> what I see

I think in particular case, not enforcing type is more the "Lua Way".

As I mentioned earlier, Lua doesn't care about the types of values in
a table to be sorted. As long as the values being compared are the
same type and support the < operator, they can be sorted. That kind of
generic programming is one of the great strengths of dynamically typed
languages. Writing a similarly generic sort function in, say, C++
requires the use of templates or a class hierarchy.

Lua similarly doesn't care about the type of the iterator function in
a for loop. All the matters is that it's callable:

   t = {9,7,4,6,3,2,0,1}
   table.sort(t)

   for k,v in next, t do
      print(k,v)
   end

   callable = setmetatable( {},
         { __call = function(t,a,b) return next(a,b) end } )
   for k,v in callable, t do
      print(k,v)
   end

Sort could work the same way, but for some reason it explicitly checks:

   1 static int sort (lua_State *L) {
   2   int n = aux_getn(L, 1);
   3   luaL_checkstack(L, 40, "");  /* assume array is smaller than 2^40 */
   4   if (!lua_isnoneornil(L, 2))  /* is there a 2nd argument? */
   5     luaL_checktype(L, 2, LUA_TFUNCTION);
   6   lua_settop(L, 2);  /* make sure there is two arguments */
   7   auxsort(L, 1, n);
   8   return 0;
   9 }

If you remove lines 4 and 5, then it will accept anything callable:

   callabe = setmetatable( {},
         { __call = function(t,a,b) return a < b end } )
   table.sort(t, callable)

If you pass it something non-callable, it does the same thing 'for'
does: it throws an error.