lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Last week, working on a Lua module, I thought about the
possibility of importing Lua functions directly from a module.

We know that table access can degrade performance, while not
much, can be considerable on more complex code.

To avoid table access, we usually see this kind of code:


local fs = require 'wax.fs'
local isdir, isfile = fs.isdir, fs.isfile


An import function can be accomplished this way (Lua 5.4):


local
function import (mod,...)
local m = require(mod)
local res = {}
for _,v in ipairs {...} do
res[#res+1] = assert(m[v])
end
return table.unpack(res)
end

local isdir, isfile =
import('wax.fs', 'isdir','isfile')

print(isdir, isfile)
-- function: 0x7fa3148b93f0 function: 0x7fa3148b9480


I played a bit with the debug module of Lua standard library and found I can change the value of an upvalue of the caller function, but not found any way to set a new upvalue.

Then I headed to Lua C api, and discovered I can basically do the same things and retrieve also an upvalue by its name but didn't found any way to create an upvalue with a new name.

The idea would make the import function acts like the local keyword avoiding the need to set the name for each variable
and also repeat the same name on import argument:


import('wax.fs', 'isdir', 'isfile')
print(isdir, isfile)
-- function: 0x7fa3148b93f0 function: 0x7fa3148b9480


I'm new to C programming, came to C just because Lua. So my doubts are the following:

1. Is there any way to create a local variable from C side on the caller using C api?

2. Is there any way to create a new upvalue from C side on the caller using C api?

3. In case (1) and (2) are impossible, is it due to some security or limitation on generated bytecode of the function once it is interpreted by Lua?


Observe that an import function is not a "must have" in Lua core or standard library. I'm just seeking for a way to implement it using the Lua as is.

_________________
Thadeu de Paula