lua-users home
lua-l archive

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


To be honest that is exactly what happened. As I didn't write the function myself and it is advanced compared to my basic lua knowledge I tracked where the output string is created and changed the return of that function. 

Indexing example:format() works and I think I can use it instead of trying to index the output of the function directly. 

Thanks for your help and detailed explanation


2016-10-17 11:46 GMT+02:00 Jonathan Goble <jcgoble3@gmail.com>:
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.)