-- 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
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
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 .
Yeah, I think dispatch tables are best when there are many functions, and the dispatching needs to be modifiable at runtime.