How would one extend a library in LUA such that:
* don’t touch the file you’re extending
* want to add another method to the class
* want to have your own custom name for the library class (i.e. not just “M”)
* KEY: have the ability for the function you add to have access to the library’s local functions. So it’s as if you put the function directly into the 3rd party Library, but in fact it’s not, you’ve separated it out into another file (your own) to avoid issues when the library file is updated
Example below: Here there is an error: “Attempt to call global ‘getANumber’ (a nil value)”. Any better ways to do it welcomed too in terms of approach.
main.lua
local myLibrary = require("library") local myLibraryExtension = require("myLibraryExtension") myLibraryExtension:extend(myLibrary) myLibrary:doX() myLibrary:doY() -- \<=== ERROR HERE
library.lua
local M = {} local function getANumber() return 55 end function M:doX() print("X", getANumber()) end return M
myLibraryExtension.lua
local M = {} local function doY() print("X", getANumber()) end function M:extend(sourceClass) sourceClass.doY = doY end return M