5
votes

Well there are no problems to push C function as function member or register C function as lua function with lua_register(L, lua_func_name, c_func);

But how tell lua what i want to pass luaFoo() as function callback param for "foober" from C? lua_pushcfunction - pushes C function, lua_pushstring pushes just a plain string, so callback field became a string, not a function.

Lua Code:

CALLBACKS = {};
FOO = 0;

function luaFoo()
FOO = FOO + 1;
end;

function addCallback(_name, _callback)
CALLBACKS[_name] = _callback;
end;

function doCallback(_name)
CALLBACKS[_name]();
end;

C code:

static int c_foo(lua_State* l)
{
  printf("FOO\n");
  return 0;
}

/*load lua script*/;
lua_State* l = /*get lua state*/;
lua_getglobal(l, "addCallback");
lua_pushstring(l, "foober");
//What push for luaFoo()
lua_pushcfunction(l, c_foo);
lua_call(l, 2, 0);

lua_getglobal(l, "doCallback");
lua_pushstring(l, "foober");
lua_call(l, 1, 0);

Similiar - if i get C functions which already registered with lua_register, how pass them as callback param from C. So we register c_foo => c_foo exist as lua function, how to tell what we want to pass "c_foo" as callback func param.

1

1 Answers

6
votes

Remember that:

function luaFoo()
  ...
end

is equivalent to this, in Lua:

luaFoo = function()
  ...
end

Therefore, your question ultimately boils down to, "I have a value in the global table. How do I push it onto the stack?" The fact that this value is a function is irrelevant; a function value in Lua is no different from an integer value, which is no different than a string value. Obviously you can do different things with them, but you just want to copy them around. That works the same regardless of what the value is.

The function you're looking for is lua_getglobal.

As for your second question, you can do it in one of two ways. You can either get the function value you registered from the global table, or you can simply re-register it with lua_pushcfunction. Since you're not using upvalues, re-registering it doesn't really have any downsides.

Oh, and one more thing, on code style. Lua doesn't require ; at the end of statements. You can do it (to make C-native programmers feel more comfortable), but it's not necessary.