Empty table in received message (SOLVED)

I’m trying to send a message to a GUI script from an enemy object with this code:

-- enemydamage.script
function on_message(self, message_id, message, sender)
    if message_id == cursor.PRESSED then
        print("Clicked!")
        msg.post("/gui#healthbars", "enemydamage", {
            currentHealth = 10,
            maxHealth = 100
        })
    end
end

I receive that message here:

-- healthbars.gui_script
function on_message(self, message_id, message, sender)
    print("Received message!")
    if message_id == hash("enemydamage") then
        print(#message)
    end
end

I get “Clicked!” and “Received message!” in the console, but also get 0 from the message table’s length. Attempting to get one of the values from that table also returns nil.

What am I doing wrong here?

#message only works if the table is “a list”, i.e. it has keys of the form 1, 2, 3, 4 etc. (starting at 1).

Try doing pprint(message) instead.

pprint is returning “{ } --[[0x10e496580]]”.

(sorry, missed that that you got a 0)

It seems strange that you would get an empty table indeed.
Are you perhaps sending this message from another place too?
Try printing the sender, to verify that it only comes from one url.

It’s printing the URL for the enemydamage script: url: [main:/enemy#enemydamage]

There’s only one enemy instance and one instance of the GUI, if that helps.

Can you make and post a zip of a minimally reproducible example project?

Something I prefer to use when communicating between GOs and GUIs is Broadcast

Found the issue while trying to make that example project. I also kinda lied to you with my OP. :frowning:

The original code looked like this:

-- enemydamage.script
function on_message(self, message_id, message, sender)
    if message_id == cursor.PRESSED then
        print("Clicked!")
        msg.post("/gui#healthbars", "enemydamage", {
            currentHealth = self.health,
            maxHealth = self.maxHealth
        })
    end
end

Looks like the table was empty because I was passing in a couple of nil values. It was originally not working even with raw values in the table, which is why I posted that… but whatever, it’s working now. Thanks for the help, and sorry for the confusion.

4 Likes