我有这样的东西:(它实际上是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 );
Run Code Online (Sandbox Code Playgroud)
我以语法清晰的方式使这些可访问.目前我将Blob对象公开为userdata并将get get和set插入metatable,使用此方法我可以这样做:
blob = Blob.new()
blob:set("greeting","hello")
print( blob:get("greeting") )
Run Code Online (Sandbox Code Playgroud)
但我更喜欢
blob = Blob.new()
blob.greeting = hello
print( blob.greeting )
Run Code Online (Sandbox Code Playgroud)
我知道这可以通过设置__indexto blob_get_value_lua和__newindexto来完成blob_set_value_lua.但是,进行此更改将破坏向后兼容性.
有没有简单的方法可以同时使用这两种语法?
只要你保持get并set发挥作用,这两种方法都会奏效.
如果你的对象是一个普通的Lua表,都__index和__newindex只为不存在的键调用.
如果您的对象(在更新中声明)是用户数据,您可以自己模拟此行为.在__index,如果键是"get"或"set",返回适当的功能.