Variables and guards in agent behaviors

14 views
Skip to first unread message

Sebastian Sardina

unread,
Feb 12, 2021, 3:55:47 PM2/12/21
to sarl

Hi,

This is just a question of style or "good SARL practice" to see what the developers think or do.

In many cases, we need want to have a guard on an agent behavior that uses some data that is extracted in the body of the behavior into a variable. But that variable is, presumably, not yet visible in the guard. How to do this clean?

Consider this:

on E_EntitySensed [MT_getEntityState(occurrence.entityName).routeLength > 0 &&
        MT_getEntityState(occurrence.entityName).charge > 0] {
        val entityName = occurrence.entityName
        val entity = MT_getEntityState(entityName)



I have to do MT_getEntityState(entityName) in the guard because I cannot yet use the variable entity

Cheers,

Sebastian







Stéphane Galland

unread,
Feb 13, 2021, 4:58:20 AM2/13/21
to sarl
Dear Sebastian.

The SARL grammar definition makes that the guard's code and the event handler's code are in different scopes and cannot share local variables.
Consequently, you cannot use your local variable entity into the guard.

In order to make your code most easy to read, I may propose to you to use the following code:

agent X {
    def getEntityState(e :  E_EntitySensed) {
        MT_getEntityState(e.entityName)
    }

    on E_EntitySensed [occurrence.entityState.routeLength > 0 && occurrence.entityState.charge > 0] {
         val entity = occurrence.entityState
    }
}

All the best.
Stéphane.

Sebastian Sardina

unread,
Feb 13, 2021, 7:48:57 PM2/13/21
to sarl
I understand guard and body are in different scopes and it should be like that.

Now, in your solution you refer to "occurrence.entityState", but event E_EntitySensed does not have any property called entityState.

The getter you defined seems to be in the agent X, not in the event.

What am I missing?

Stéphane Galland

unread,
Feb 17, 2021, 6:51:23 AM2/17/21
to sarl
Dear Sebastian.

"occurrence.entityState" is equivalent to "occurrence.getEntityState" that is equivalent to "getEntityState(occurrence"). (Documentation: http://www.sarl.io/docs/official/reference/general/Extension.html, local extension method)

All the best.

Sebastian Sardina

unread,
Mar 2, 2021, 1:35:55 AM3/2/21
to sarl
Got it, thanks!
Reply all
Reply to author
Forward
0 new messages