简体   繁体   中英

How to get lua function as parameter in C++ and then call it

I'm implementing lua api (5.1) in C++ and got problem, couldn't pass lua function as paramater in c++ function called from lua. Example (Main function is called from C++):

Lua:

function Main()
    HookEntityFunction("player", 1, PlayerSpawn); -- << is this normal?
end

function PlayerSpawn()

end

C++:

int HookEntityFunction(lua_State *L)
{
    lua_CFunction F = lua_tocfunction(L, 3); -- << how to call it?
}

The answer you posted in your question is incorrect, or at least silly.

The reason your original code doesn't work is that lua_tocfunction is, as the name suggests, only for C functions. It takes a C function that's been exposed to Lua, and re-extracts the function pointer to it. Since a native Lua function had no corresponding C function, lua_tocfunction won't work with it.

Your proposed solution relies on the passed-in function being stored as a global, and getting it based on its name. That puts it on the stack. But in your first example, it was already on the stack! That's the correct, idiomatic way to deal with Lua objects from C functions: by manipulating the stack.

So the real solution to your problem is, take your first Lua snippet, and just do lua_call(L, 0, 0) . No need for globals or pointers or anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM