lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I would like to make this example work:

buffer = canvas:create(10, 10);

buffer:drawImage("teste.png");

canvas:drawImage(buffer);

... my code is this:

void LuaCanvasBinding::Register(lua_State* L)
{
  lua_newtable(L);
  int methodtable = lua_gettop(L);
 
  luaL_newmetatable(L, className);
  int metatable = lua_gettop(L);
   
  lua_pushliteral(L, "__metatable");
  lua_pushvalue(L, methodtable);
  lua_settable(L, metatable);  // hide metatable from Lua getmetatable()

  lua_pushliteral(L, "__index");
  lua_pushvalue(L, methodtable);
  lua_settable(L, metatable);

  lua_pushliteral(L, "__gc");
  lua_pushcfunction(L, _lua_gc);
  lua_settable(L, metatable);

  lua_pop(L, 1);  // drop metatable

  lua_register(L, className, _lua_create);

  lua_pop(L, 1);  // drop methodtable
}

int LuaCanvasBinding::_lua_create(lua_State *L)
{
  puts("lua canvas create");
  luaL_newlib(L, methods);

  return 1;
}

int LuaCanvasBinding::create(lua_State *L)
{
  LuaCanvasBinding *c = NULL;

  printf(":Create top: %d\n", lua_gettop(L));
  if (lua_gettop(L) == 1) {
      const char *image = (const char *)luaL_checkstring(L, 1);

    c = new LuaCanvasBinding(image);
  } else if (lua_gettop(L) == 2) {
    int w = (int)luaL_checknumber(L, 1),
        h = (int)luaL_checknumber(L, 2);

    c = new LuaCanvasBinding(w, h);
  } else if (lua_gettop(L) == 3) {
    const char *img = (const char *)luaL_checkstring(L, 1);
    int w = (int)luaL_checknumber(L, 2),
        h = (int)luaL_checknumber(L, 3);

    c = new LuaCanvasBinding(img, w, h);
  }

  lua_boxpointer(L, c);
  luaL_getmetatable(L, className);
  lua_setmetatable(L, -2);

  return 1;
}

... and the main.cpp is:

  _luaL = luaL_newstate();
 
  if (_luaL == NULL) {
    return;
  }

  luaL_openlibs(_luaL);
 
  LuaSettingsBinding::Register(_luaL, directory, filename);
  LuaCanvasBinding::Register(_luaL);

  std::string path = _directory + "/" + _filename.c_str();

  if (luaL_loadfile(_luaL, path.c_str()) == 0) {
    if (lua_pcall(_luaL, 0, 0, 0) != 0) {
      printf("Player pcall:: error\n");
    }
  }

... apparently, LuaCanvasBinding::create(lua_State *L) returns the userdata, but I cannot use this object like a "canvas".

I'm using the lua 5.2.1. Anybody can help me ?


--
Jefferson Ferreira