lua-users home
lua-l archive

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


> Question: should it be possible to distinguish between a table and a
> function of one parameter? That is, does Lua really need both foo()
and
> foo[] syntaxes?

function formatter(fn)
	local mt = { _fmt=fn or string.upper }
	return setmetatable(mt, {
		__call = function(t,...) print(mt._fmt(unpack(arg)))
end,
		__newindex = function(t,k,v)
				if k=='fn' then mt._fmt=v
				else assert(false, 'bad attrib')
				end
			end,
		})
end

f = formatter()
f('abc')
f.fn = string.lower
f('Abc')

Gives:
ABC
abc

Not sure if this example is a convincing argument, but you can have
stateful, callable objects with both syntaxs allowed. The other reason
is just clarity. It's easier to read code where you can distinguish
between mapping types and callable objects. (How would you assign to a
function with one arg?)

What I'd rather have is get and set meta-methods rather than index and
newindex. Or perhaps get, set and new.

Nick