lua-users home
lua-l archive

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


On Mon, Oct 17, 2016 at 5:19 AM, Hur Butun <hurbutun@gmail.com> wrote:
> @Jonathan,
>
> I am trying to index the output of the function. I define parameters with
> unit with 'new' subfunction such as:
> pv=require('physvalue')
> myElec = pv:new('',450, 'W')
>
> With this myElec is a table with 'value' and 'unit' indices. However if I
> try to index it such as
> myElec.unit
>
> I get nil although in the 'unit' index of the table output of the function
> it is 'W'

No, `myElec` is an instance of the `PhysValue` class. That instance
does not contain the fields you are looking for. In order to get the
table with those fields, you must call the instance's `format()`
method, which (as modified by you) returns the table with those
fields.

I think the possible source of confusion is that the original version
of the module gives PhysValue instances a __tostring metamethod that
simply delegates to format(). Therefore, I think you may have just
typed (to use your example here) `pv:new('', 450, 'W')` into the Lua
prompt, gotten the string output by format(), tracked down where that
string was generated, and changed that thinking that it would change
the return value of the pv:new() call.

But it doesn't; pv:new() still returns a PhysValue instance. When you
just type in an expression (such as the pv:new() call), Lua, in an
attempt to be helpful, automatically calls tostring() on the value of
the expression (here, the PhysValue instance returned by pv:new) to
get a "nice" output. When you assign the return value to a variable,
however, that doesn't happen, so here you need to do that explicitly
by calling the format() method.

Does that make sense? (It's 5:45 AM here and I need to get to bed, so
apologies if I'm sleepy-rambling.)