Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wrap simple function pointers #45

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions include/LuaContext.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2272,16 +2272,24 @@ struct LuaContext::Pusher<TReturnType (TParameters...)>
// when the lua script calls the thing we will push on the stack, we want "fn" to be executed
// since "fn" doesn't need to be destroyed, we simply push it on the stack

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// we wrap the function pointer so we can store it in a userdata

struct wrap {
TReturnType (*fn)(TParameters...);
};

// this is the cfunction that is the callback
const auto function = [](lua_State* state_) -> int
{
// the function object is an upvalue
const auto toCall = reinterpret_cast<TReturnType (*)(TParameters...)>(lua_touserdata(state_, lua_upvalueindex(1)));
auto wrapper = (struct wrap *) lua_touserdata(state_, lua_upvalueindex(1));

const auto toCall = wrapper->fn;
return callback(state_, toCall, lua_gettop(state_)).release();
};

// we copy the function object onto the stack
lua_pushlightuserdata(state, reinterpret_cast<void*>(fn));
// we make a userdata to hold the function's address
auto wrapper = (struct wrap *) lua_newuserdata(state, sizeof(void*));

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// and we store the function pointer inside it

wrapper->fn = fn;

// pushing the function with the function object as upvalue
lua_pushcclosure(state, function, 1);
Expand Down