lua-users home
lua-l archive

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


>  x:do_something(5)  -- Clearly should be a function.
>  x:name()  -- Called as a function, even though it's just data?
>  x.name    -- Returned as a string -- is this better?
>
> Aesthetically the last one seems more pleasing, since it makes clear
> that it's just returning some data.  But what do you all as Lua
> programmers expect?  I guess one downside of the second is that
> it might suggest that you can set it also, which is not allowed
> for my type:


Programmers expect what is documented. I don't think your ideas are at
all unusual in the Lua world.  Userdata objects in a lot of the code I
write have both methods and properties/attributes where properties are
accessed and set just like in your 3rd example x.name.  I don't think
it necessarily suggests that users can write to it since people are
probably familiar with the idea that properties can be read-only.


> As a second question, most user-defined C types seem to be
> constructed with "new()" functions (eg. mytype.new().  Is there
> any precedent for using the __call metamethod to make construction
> look like a function call?
>
>  x = mytype()


I also do this.  The really nice part about implementing a different
access patter for properties as compared to methods is that you can
automatically derive a "prototype" constructor from the list of
settable properties.  For example, if I have a Window userdata class
with the properties fullscreen, title, dim, etc., I can do the
following:

local win = Window()
win.fullscreen = true
win.dim = {512, 512}
win.title = "My Window"

If all settable attributes can be set with what I typically call a
"prototype constructor", you can do this:

local win = Window{
   fullscreen = true,
   dim = {512, 512},
   title = "My Window",
}

When the __call on Window is called, all you have to do is iterate
over the table and call into settable properties with the value of the
property given.  No duplicate code is required since everything is
given in the class metatable.

wes