Greg
Greg

Reputation: 34818

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

How would one extend a library in Lua such that:

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

Upvotes: 2

Views: 2344

Answers (1)

hjpotter92
hjpotter92

Reputation: 80649

You can not call the getANumber function from your myLibraryExtension.lua file. The local function exists only in the library.lua scope and can't be used outside for the reason as explained in comments by hugomg. If you want access to private (read local) function, you can modify scripts like this:

library.lua

Add the following statement before return M

M.getANumber = getANumber

myLibraryExtension.lua

Modify the function doY a little:

local function doY(this)
    print("X", this.getANumber())
end

What happens is, when you execute the statement

myLibrary:doY()

lua executes it as follows:

myLibrary.doY( myLibrary ) -- yes, myLibrary is passed as an argument too

You can use the passed reference to the library to your benefit by extending the doY function to accept an argument as well (this in my case).

This object can then have the access to the desired local function.

Upvotes: 2

Related Questions