A Lua technique to avoid if-else statements in on_message() callback

--  test.script
local OnMessage = require("om")

OnMessage {
    [hash "greet"] = function(self, message, sender)
        print("Hello")
    end,

    [hash "game_over"] = function()
        go.delete()
    end
}

--  om.lua
local function _()
end

return function(message_callbacks)
    function on_message(self, message_id, message, sender)
        (message_callbacks[message_id] or _)(self, message, sender)
    end
end
2 Likes

It is good to try out things like this:-) And useful to realise that in this case it is not a good idea. This is obfuscation. It does not avoid if-else, it writes it in a much more complicated way. I suggest looking at this pattern, as another way of writing if-else:
a = b and c or d

OP is creating a dispatch table, which is a pretty well-established pattern.

4 Likes

Ah yes, interesting. I tried this in Defold a while ago (although I did not know what it was called), using tests as table keys, with functions as content. It is kinda OK if it replaces a long list of if-else’s, otherwise using if-else’s I think is better. My thinking being that (at least for for small bits of code) it is better to use (real) core language rather than creating language features to use. Also if the list gets long, put it all in a function. Although I am arguing with myself about this as I write :rofl:.

1 Like

Yeah, I think dispatch tables are best when there are many functions, and the dispatching needs to be modifiable at runtime.

2 Likes