Lua: can I use “require” as a form of dependency injection?

若如初见. 提交于 2019-12-06 12:34:33

Step 1: Stop thinking like a Java programmer.

You're in Lua now. There are no classes with explicit and compile-time fixed prototypes. Functions are first-class objects; they are values. So break the problem down in that way.

You have a bunch of "rules" (ie: functions). You want to apply some of those rules to certain data. You have a configuration system that says, "When applying rules to data from location X, use this set of rules." So... do that.

You detect that data comes from location X. So you call your configuration logic to build a Lua table for location X that contains your rules (ie: functions) to apply to that data. The configuration logic for location X loads the rules from wherever they are stored, and returns them. If the configuration is in a database or something, then the database entry for location X would probably refer to rules by name.

How you convert that rule name into an actual Lua function is up to you, but there are many ways. You could have a registry that preloads all of the Lua files from a directory into a table, and then pick the rule based on names in that table. Or perhaps you have a database of named Lua files/scripts, each of which is a separate rule. There are any number of ways to implement this.

In Lua, "dependency injection" is just "deciding how to build collections of functions." It's not a special thing because Lua is a much more free-form language than Java. It's just a matter of where the functions come from, how to put them together in a table, and then how to apply that table to some data. And all of those are up to you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!