开发者

Creating callback functions in Lua

I have a c++ class that organizes parts on a screen that can be drawn to, called Canvases.

I want to create those canvasses from Lua (which I already do), the C++ code keeps track of them and renders them to the screen.

But to draw into a canvas, I want to be able to make that available from LUA, so what I want is to say something like this:

local c1 = foo.createCanvas("test", 60, 60, 300, 200);
c1:onPaint = function(params)
  self:clear(1, 0, 0, 1);
  self:moveTo(10, 10);
  self:lineTo(100, 100);
end

createCanvas are functions inside foo, clear, moveTo, lineTo are function of the canvas object that is created by createCanvas.

So now, when foo starts rendering everything, it should see that an onPaint function has been defined in canvas "test" and that this function should first be called before rendering to screen.

How should I do this?

the canvas is a lua metatable object in C++ with a __index and __newindex declared. I presume that I should take the __newindex to find out that onPaint will be defined. How can I get this function?

boost::shared_ptr<Canvas> **pppCanvas = (boost::shared_ptr<Canvas> **)luaL_checkudata(L, 1, "Canvas");
std::string key = lua_tostring(L, 2);
if (key == "onPaint")
{
    // sometype x = lua_tofunction(L, 3);???
}
else
    luaL_error(L, "Canvas - member '%s' is not defined", key.c_str());
return 0;

So what type should I use, what function should I use to get this function to?

And then, how will I call this lua-function? And how will I find out if the function has been defined in the first place?

EDIT:

I found this topic: click It shows how to make a reference to a lua-function and as开发者_开发百科k it back later. The only problem now is: luaL_ref doesn't take a stack index, so I don't know how to take the function from the stack in my above __newindex function.

My problem is solved now (can't seem to set this problem to solved because of low reputation) because I actually need the last item on the stack. But I would like to know if anyone knows how I can take another item in the stack.

Anyway: PROBLEM SOLVED

D.


Seems you can use lua_call to fulfill your need. Note that swig does not support director in lua afaik and is thus not an option.

EDIT: Updated according to your example:

lua_getfield(L, LUA_GLOBALSINDEX, "myLuaFunctionToCall"); /* function to be called */
lua_pushinteger(L, 3); // parameter is 3
lua_call(L, 1, 1); //call with 1 parameter, 1 result
lua_getfield(L, LUA_GLOBALSINDEX, "myLuaFunctionToCall"); /* function to be called */
lua_Number result = lua_tonumber(L,1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜