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 对象公开为用户数据,并将 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
。然而,进行此更改将破坏向后兼容性。
有没有什么简单的方法可以同时拥有两种语法?
I have something like this:
(Its actually C++ but in this simplified form there's nothing C++ specific in it)
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 );
I make these accessible in a syntactically clean way. Currently I expose the Blob object as a userdata and plug get and set into the metatable, using this I can do:
blob = Blob.new()
blob:set("greeting","hello")
print( blob:get("greeting") )
But I'd prefer
blob = Blob.new()
blob.greeting = hello
print( blob.greeting )
I know this can be done by setting the __index
to blob_get_value_lua
and __newindex
to blob_set_value_lua
. However making this change will break backward compatibility.
Is there any easy way to have both syntaxes at the same time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要您保留
get
和set
函数,这两种方法都可以工作。如果您的对象是常规 Lua 表,则仅针对不存在的键调用
__index
和__newindex
。如果您的对象(如您在更新中所述)是用户数据,您可以自己模拟此行为。在
__index
中,如果键是"get"
或"set"
,则返回适当的函数。As long as you will keep
get
andset
functions, both approaches will work.If your object is a regular Lua table, both
__index
and__newindex
will be called only for non-existant keys.If your object (as you state in the update) is an userdata, you can simulate this behaviour yourself. In
__index
, if the key is"get"
or"set"
, return an appropriate function.