Page 1 of 1

test if member of lua object exists ?

Posted: Sun May 22, 2016 10:08 pm
by binbinhfr
Hi,

I have a simple LUA question:
LUAentity contains "backer_name" that is only instancied for trainstops and labs.

If, for example, I want to check the content of player.selected and test if
backer_name exits on the selected entity, how can I do it without making factorio
stop for a LUA error ?
I tried testing player.selected.backer_name is nil. It does not work...
I tried testing type(player.selected.backer_name) is nil . Neither...

any idea ?

I could check the prototype to test for lab or trainstop like
selected.type == "train-stop" or selected.type == "lab"
But imagine the devs adds one day another entity with backer_name...
I would like something more proofed. ;)

Re: test if member of lua object exists ?

Posted: Mon May 23, 2016 9:30 am
by ArderBlackard
You may try to perform indexing the required member wrapped with pcall():

Code: Select all

function get_member_safe( table, key )
  local call_result, value = pcall( function () return table[key] end )
  if call_result then
    return value
  else
    return nil
  end
end

Re: test if member of lua object exists ?

Posted: Mon May 23, 2016 11:11 am
by binbinhfr
Yes thanks for the idea.
I thought about pcall too, but I was wondering if there was something lighter in LUA.

Re: test if member of lua object exists ?

Posted: Mon May 23, 2016 12:08 pm
by ArderBlackard
As far as I can see, entities are implemented as proxy tables so they do not actually contain any of the members - they are provided by their metatables and accessing them generates error for non-existent fields instead of simply returning nil.