用于面向对象访问的 C 和 lua 元表



我有这样的东西:(它实际上是c++,但在这种简化形式中没有特定于c++的内容)

struct Blob;
// Some key-value accessors on Blob
char * blob_get_value( Blob * b, char * key );
void set_value( Blob * b, char * key, char * value); 

//Some lua wrappers for these functions
int blob_get_value_lua( lua_State * L );
int blob_set_value_lua( lua_State * L );

我以一种语法清晰的方式使它们易于访问。目前,我将Blob对象作为userdata公开,并将get和set插入元表,我可以这样做:

blob = Blob.new()
blob:set("greeting","hello")
print( blob:get("greeting") )

但我更喜欢

blob = Blob.new()
blob.greeting = hello
print( blob.greeting )

我知道这可以通过将__index设置为blob_get_value_lua__newindex设置为blob_set_value_lua来完成。但是这样做会破坏向后兼容性。

有什么简单的方法可以同时使用这两种语法吗?

只要您保留getset函数,两种方法都可以工作。

如果你的对象是一个普通的Lua表,__index__newindex只会被不存在的键调用。

如果您的对象(如您在更新中所述)是userdata,您可以自己模拟此行为。在__index中,如果键为"get""set",则返回相应的函数

最新更新