Is there a way to programmatically determine in C / C ++ how many parameters the Lua function expects?

Is there a way to determine how many parameters the Lua function executes before calling it from C / C ++ code?

I looked at lua_Debugand lua_getinfo, but they don't seem to provide what I need.

This may seem a bit like I'm going against the spirit of Lua, but I really want to skip the proof of the interface that I have between Lua and C ++. When a C ++ function is called from Lua code, the interface verifies that Lua provided the correct number of arguments, and the type of each argument is correct. If a problem is found with arguments a lua_error.

I would like a similar error checking to be the other way around. When C ++ calls the Lua function, it should at least verify that the Lua function does not declare more parameters than necessary.

+3
source share
5 answers

What you are asking is not possible in Lua.

You can define a Lua function with this set of arguments:

function f(a, b, c)
   body
end

However, Lua does not impose a limit on the number of arguments that you pass to this function.

It's really:

f(1,2,3,4,5)

Additional parameters are ignored.

This is also true:

f(1)

The remaining arguments are assigned 'nil'.

Finally, you can define a function that takes a variable number of arguments:

function f(a, ...)

At this point, you can pass any number of arguments to the function.

. 2.5.9 Lua.

, , - Lua, , .

+5

, upvalues ​​ Lua 5.2, 'u' nups, nparams, isvararg get_info(). Lua 5.1.

+4

Lua, Lua, . Lua , .

, :

function do_nothing() end

full_api = {}
function full_api:callback(a1, a2) print(a1, a2) end

lazy_impl = {}
lazy_impl.callback = do_nothing

( ) .

, . - Metalua.

+2

, Lua. , , . Lua , , nil ( - name = name or "Bruce" ) , (if not name then error"Name required" end , if not name then return nil, "name required" end ). Lua , , Lua C.

, , , , , . , . , MetaLua . Lua .

, , , ( ) Lua, lua_pcall(), lua_call(), .

+1

. , Lua C lua_CFunction. Lua Lua lua_CFunction. lua_CFunction , .

On the other hand, what you can do is provide a system for function authors (whether in pure Lua or C) to advertise how many parameters their functions expect. After creating the function (function f (a, b, c)) they simply pass it to the global function (register (f, 3)). Then you can extract this information from your C ++ code, and if the function does not report its parameters, then cancel what you have now. With such a system, you can even advertise the type expected by the parameters.

+1
source

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


All Articles