0

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?
}
3
  • If you want to answer your own question, then please post it as an actual answer. Commented Aug 19, 2018 at 20:36
  • Yes it is possible when not: We are no longer accepting answers from this account. See the Help Center to learn more. Commented Aug 19, 2018 at 20:38
  • 1
    @BeqaGurgenidze: If you've been answer-banned, that's unfortunate. However, that doesn't mean you get to post answers in the question. Commented Aug 19, 2018 at 21:05

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I wan't to get function pointer and then call it when i want. (Writing call function was a bad idea). I'm new to Lua.
As I explained in my answer, you cannot get a C function pointer to a Lua function, because a Lua function is not a C function. If you want to hold on to the function object for later on the C side, you can use luaL_ref with the registry. See stackoverflow.com/questions/8557304/calling-lua-from-c

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.