lua-users home
lua-l archive

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


2012/11/16  <AllanPfalzgraf@eaton.com>:

> Yes, the intent would be to have a name (variable) permanently
> set to a certain type.

This is already possible. Let me spell out how.

Lua has no variables (i.e. preallocated named blocks of memory
the contents of which may change), only names and values. Lua names
are not independent entities. They are indices into the global
environment. The following statements do the same:

    a = b/c
    _ENV.a = b/c
    _ENV["a"] = b/c

I.e. all Lua assignments involve a table, and you can intercept
those assignments as explained in "Programming in Lua" or Steve's
StrictStruct article on the Lua Wiki. You provide _ENV with
a metatable that overrides the __newindex metamethod.

The new metamethod can do anything you like whenever something is
assigned into that table: checking properties of that particular
name or that particular value, extra processing of the value,
logging to a file, emitting an audible beep, controlling your
media player, whatever. Including, but not limited to, checking
whether that name may accept values of that type.

So a much more powerful feature than assigment type checking
lies waiting to be exploited.

> One advantage would be that there is no special syntax needed within
> operations, such as divide, when the type is fixed. If the assignment
> in the divide operation is to an integer, the result will be an
> integer without the need for a "//" instead of a "/" operator.

A truly context-dependent compilation to invoke different operators
depending on where the result goes is not so simple to achieve; not
even statically-typed languages with huge compilers like Fortran
or C can manage that.

But if you just keep the standard division, the __newindex metamethod
can say oops, the target is designated integer and you're giving me
a float, I need to floor the result; or give an error message, whatever.
Once again, that powerful tool can handle it.

Dirk