How to extend a library with access to it's local functions?

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() &nbsp; -- \<=== 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

Does this fix it?

main.lua

myLibrary = require(“library”) --Can’t be local so that myLibraryExtension can access it require(“myLibraryExtension”) myLibrary:doX() myLibrary:doY()   – <=== ERROR HERE

library.lua

local M = {} function M:getANumber() return 55 end function M:doX() print(“X”, M:getANumber()) end return M

myLibraryExtension.lua

function myLibrary:doY() print(“X”, myLibrary:getANumber()) end

thanks atrizhong - I note you’ve actually modified the “library.lua” file which is what I was trying to avoid.  However I don’t think there is another way to meet the requirements I had anyway, so it seems I would have to do what you’re suggesting…

Does this fix it?

main.lua

myLibrary = require(“library”) --Can’t be local so that myLibraryExtension can access it require(“myLibraryExtension”) myLibrary:doX() myLibrary:doY()   – <=== ERROR HERE

library.lua

local M = {} function M:getANumber() return 55 end function M:doX() print(“X”, M:getANumber()) end return M

myLibraryExtension.lua

function myLibrary:doY() print(“X”, myLibrary:getANumber()) end

thanks atrizhong - I note you’ve actually modified the “library.lua” file which is what I was trying to avoid.  However I don’t think there is another way to meet the requirements I had anyway, so it seems I would have to do what you’re suggesting…