如何在 Lua-C API 5.2 中创建类对象? [英] How do I create a class object in Lua-C API 5.2?

查看:26
本文介绍了如何在 Lua-C API 5.2 中创建类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Lua 封装一个 C 函数,使用 Lua 5.2 的 Lua-C API:

I'm wrapping a C function with Lua, using the Lua-C API for 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
");
  return 0;
}
int foo_newindex(lua_State* L) {
  printf("## __newindex
");
  return 0;
}
int foo_index(lua_State* L) {
  printf("## __index
");
  return 0;
}
int foo_dosomething(lua_State* L) {
  printf("## dosomething
");
  return 0;
}
int foo_new(lua_State* L) {
  printf("## new
");

  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 时:

When I run this Lua:

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

...我看到这个输出(有错误):

...I see this output (with error):

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

我做错了什么?

推荐答案

好的,搞定了.我不得不将 __index__metatable 添加到 Foo 的新元表中,如下所示:

Ok, got it working. I had to add __index and __metatable to Foo's new metatable, as shown below:

void register_foo_class(lua_State* L) {
  int lib_id, meta_id;

  /* newclass = {} */
  lua_createtable(L, 0, 0);
  lib_id = lua_gettop(L);

  /* metatable = {} */
  luaL_newmetatable(L, "Foo");
  meta_id = lua_gettop(L);
  luaL_setfuncs(L, _meta, 0);

  /* metatable.__index = _methods */
  luaL_newlib(L, _methods);
  lua_setfield(L, meta_id, "__index");  

  /* metatable.__metatable = _meta */
  luaL_newlib(L, _meta);
  lua_setfield(L, meta_id, "__metatable");

  /* class.__metatable = metatable */
  lua_setmetatable(L, lib_id);

  /* _G["Foo"] = newclass */
  lua_setglobal(L, "Foo");
}

这篇关于如何在 Lua-C API 5.2 中创建类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆