Как создать объект класса в Lua-C API 5.2?

Я оборачиваю функцию C в Lua, используя Lua-C API для Lua 5.2:

#include <lua.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <stdio.h>

int foo_gc();
int foo_index();
int foo_newindex();
int foo_dosomething();
int foo_new();

struct foo {
  int x;
};

static const luaL_Reg _meta[] = {
    {"__gc", foo_gc},
    {"__index", foo_index},
    {"__newindex", foo_newindex},
    { NULL, NULL }
};
static const luaL_Reg _methods[] = {
    {"new", foo_new},
    {"dosomething", foo_dosomething},
    { NULL, NULL }
};

int foo_gc(lua_State* L) {
  printf("## __gc\n");
  return 0;
}
int foo_newindex(lua_State* L) {
  printf("## __newindex\n");
  return 0;
}
int foo_index(lua_State* L) {
  printf("## __index\n");
  return 0;
}
int foo_dosomething(lua_State* L) {
  printf("## dosomething\n");
  return 0;
}
int foo_new(lua_State* L) {
  printf("## new\n");

  lua_newuserdata(L,sizeof(Foo));
  luaL_getmetatable(L, "Foo");
    lua_setmetatable(L, -2); 

  return 1;
}

void register_foo_class(lua_State* L) {
    luaL_newlib(L, _methods); 
  luaL_newmetatable(L, "Foo");
  luaL_setfuncs(L, _meta, 0);
  lua_setmetatable(L, -2);
  lua_setglobal(L, "Foo");
}

Когда я запускаю этот Lua:

local foo = Foo.new()
foo:dosomething()

...я вижу этот вывод ( с ошибкой):

## new
## __index
Failed to run script: script.lua:2: attempt to call method 'dosomething' (a nil value)

Что я делаю неправильно?

11
задан tony19 27 July 2019 в 10:28
поделиться