Using the 'module' function in Lua 5.2?

I have a VC ++ project that uses Lua 5.2 for scripting.
I am trying to implement MySQL compatibility in this project.
I do not own this project, so I would prefer to change as little as possible of the source code, if any.
I downloaded and unpacked the files from this extension into the same base directory as the executable ... and in my Main.lua file, I have added the require('DBI') , as indicated, to do this on this wiki page .

But when I launch the application and execute the script, I get:

 LUA Fail: C:\Path\To\bin\DBI.lua:3: attempt to call global 'module' (a nil value) 

After some easy reading, I found out that the module function was depreciated in Lua 5.2 ...
But this extension, as well as other MySQL extensions, require the use of a module function.

So what is the workaround for this problem?

+3
source share
2 answers

You may need to compile your Lua instance with LUA_COMPAT_MODULE; according to the source code: "LUA_COMPAT_MODULE controls compatibility with the modules of the previous module modules (Lua) and" luaL_register "(C)".

This will not be enough, since the module itself is written using the Lua 5.1 API. You can either try to find its version of Lua 5.2, or use something like Peter Cawley TwoFace , which "allows Lua 5.2 to load most 5.1 C libraries without having to recompile."

+2
source

I used this as a quick and dirty way to get most of the script settings working with 5.2. I myself did not use the module, but in my stack, for example, luasocket, copas, etc. I doubt this helps in your particular case, but may be more general.

Essentially, I replicated the version of the C module in lua using the debug library to set up the function environment. Not really, but hey.

 if not module then function module(modname,...) local function findtable(tbl,fname) for key in string.gmatch(fname,"([%w_]+)") do if key and key~="" then local val = rawget(tbl,key) if not val then local field = {} tbl[key]=field tbl = field elseif type(val)~="table" then return nil else tbl = val end end end return tbl end assert(type(modname)=="string") local value,modul = package.loaded[modname] if type(value)~="table" then modul = findtable(_G,modname) assert(modul,"name conflict for module '"..modname.."'" ) package.loaded[modname] = modul else modul = value end local name = modul._NAME if not name then modul._M = modul modul._NAME = modname modul._PACKAGE = string.match(modname,"([%w%._]*)%.[%w_]*$") end local func = debug.getinfo(2,"f").func debug.setupvalue(func,1,modul) for _,f in ipairs{...} do f(modul) end end function package.seeall(modul) setmetatable(modul,{__index=_G}) end end 
+1
source

Source: https://habr.com/ru/post/1483876/


All Articles