test if member of lua object exists ?

Place to get help with not working mods / modding interface.
User avatar
binbinhfr
Smart Inserter
Smart Inserter
Posts: 1525
Joined: Sat Feb 27, 2016 7:37 pm
Contact:

test if member of lua object exists ?

Post 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. ;)
My mods on the Factorio Mod Portal :geek:
User avatar
ArderBlackard
Long Handed Inserter
Long Handed Inserter
Posts: 74
Joined: Thu May 05, 2016 12:41 pm
Contact:

Re: test if member of lua object exists ?

Post 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
Gib dich hin bis du Glück bist
User avatar
binbinhfr
Smart Inserter
Smart Inserter
Posts: 1525
Joined: Sat Feb 27, 2016 7:37 pm
Contact:

Re: test if member of lua object exists ?

Post by binbinhfr »

Yes thanks for the idea.
I thought about pcall too, but I was wondering if there was something lighter in LUA.
My mods on the Factorio Mod Portal :geek:
User avatar
ArderBlackard
Long Handed Inserter
Long Handed Inserter
Posts: 74
Joined: Thu May 05, 2016 12:41 pm
Contact:

Re: test if member of lua object exists ?

Post 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.
Gib dich hin bis du Glück bist
Post Reply

Return to “Modding help”