C 和 Lua 的 metatable 用于面向对象访问。

我有这样的一些代码: (其实是 C++ 代码,但是在这个简化的形式中,它没有 C++ 特定的内容)

struct Blob;

// Blob 上一些关键-值访问器
char * blob_get_value( Blob * b, char * key );
void set_value( Blob * b, char * key, char * value);

// 上述函数的一些 lua 封装
int blob_get_value_lua( lua_State * L );
int blob_set_value_lua( lua_State * L );

我以一种语法干净的方式将它们暴露出来。目前,我将 Blob 对象作为 userdata 暴露,并将 get 和 set 插入到 metatable 中,使用这个方法,我可以做到:

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 来实现这一点。但是,这样的更改将破坏向后兼容性。

有没有一种简单的方法可以同时拥有这两种语法?

原文链接 https://stackoverflow.com/questions/5799893

点赞
stackoverflow用户6236
stackoverflow用户6236

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

如果您的对象是普通的 Lua 表格,则仅在不存在键时调用 __index__newindex

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

2011-04-27 06:47:32